PHP round($num,2) and javascript toFixed(2) is not

2019-09-15 09:51发布

问题:

I have one php function and having

phpans = round(53.955,2)

and javascript function

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

both jsans and phpans is giving different $phpans = 53.96 ans jsans = 53.95 . I can not understand why this is happening .. Thanks is Advance

回答1:

Because computers can't represent floating numbers properly. It's probably 53.95400000000009 or something like that. The way to deal with this is multiply by 100, round, then divide by 100 so the computer is only dealing with whole numbers.

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

//Outputs
"53.95"
53.96


回答2:

JAvascript toFixed: The toFixed() method converts a number into a string, keeping a specified number of decimals.

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

Conclusion tofixed not working like php round. precision Specifies the number of decimal digits to round to.

Javascript function :

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

    return result;
}