PHP round($num,2) and javascript toFixed(2) is not giving right output for this value 53.955

為{幸葍}努か 提交于 2019-12-12 04:46:48

问题


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;
}


来源:https://stackoverflow.com/questions/43802830/php-roundnum-2-and-javascript-tofixed2-is-not-giving-right-output-for-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!