PHP round($ num,2)和javascript toFixed(2)没有为该值提供正确的输出53.955 [英] PHP round($num,2) and javascript toFixed(2) is not giving right output for this value 53.955

查看:51
本文介绍了PHP round($ num,2)和javascript toFixed(2)没有为该值提供正确的输出53.955的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个php函数,并且具有

I have one php function and having

phpans = round(53.955,2)

和javascript函数

and javascript function

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

jsans和phpans都给出了不同的 $ phpans = 53.96 ans jsans = 53.95 .我不明白为什么会这样..谢谢,谢谢

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

推荐答案

因为计算机无法正确表示浮点数.大概是53.95400000000009或类似的东西.处理此问题的方法是先乘以100,四舍五入然后再除以100,这样计算机就只能处理整数.

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

这篇关于PHP round($ num,2)和javascript toFixed(2)没有为该值提供正确的输出53.955的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆