问题描述
我有一个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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!