Search code examples
javascriptnode.jsfractions

Fixed precision always in js 0.5 -> 0.5000


I am trying to fix every fraction number up to n decimal place. But in javascript/nodejs it seems not possible to convert 0.5 to 0.5000. Due to which my test cases which expect 0.5000 fails.

Any idea how can I do this in nodejs/javascript?


Solution

  • As others said Number.prototype.toFixed() should work for you. I tried my hands on and this works perfectly.

    function plusMinus(arr) {
    let length = arr.length;
    let o = arr.reduce((acc,cv)=>{
        if(cv > 0){
            acc.pos++;  
         }
        else if(cv<0){
            acc.neg++;
        }
        else{
            acc.zero++;
        }
        return acc;
    },{pos:0,neg:0,zero:0});
        console.log((o.pos/length).toFixed(4));
        console.log((o.neg/length).toFixed(4));
        console.log((o.zero/length).toFixed(4));
    }
    plusMinus([-4,3,-9,0,4,1]);