PHP round ($ num, 2) and javascript toFixed (2) do not give correct output for this value 53.955

I have one php function and

phpans = round(53.955,2)

and the javascript function

var num  = 53.955;
var jsans = num.toFixed(2);
console.log(jsans);
      

Run code


both jsans and phpans provide different $ phpans = 53.96 ans jsans = 53.95 . I don't understand why this is happening. Thanks Advance

0


source to share


2 answers


Because computers cannot represent floating numbers correctly. It's probably 53.95400000000009 or something like that. The way to deal with this is multiplying by 100, rounding, and then dividing by 100, so the computer only deals with integers.



var start = 53.955,
        res1,
        res2;
    
    res1 = start.toFixed(2);
    res2 = (start * 100).toFixed(0) / 100;
    console.log(res1, res2);
      

Run code


//Outputs
"53.95"
53.96

      

+3


source


JAvascript toFixed: The toFixed () method converts a number to a string, keeping the specified number of decimal places.

php round: Returns the rounded val to the specified precision (number of digits after the decimal point). precision can also be negative or zero (default).

Conclusion tofixed doesn't work like php round. accuracy . Specifies the number of decimal digits rounded to.



Javascript function:

function round_up (val, precision) {
    power = Math.pow (10, precision);
    poweredVal = Math.ceil (val * power);
    result = poweredVal / power;

    return result;
}

      

0


source







All Articles