在JavaScript中使用Math.round会在最后添加奇怪的0 [英] Using Math.round in javascript adds weird number of 0s at the end

查看:164
本文介绍了在JavaScript中使用Math.round会在最后添加奇怪的0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


<强>可能重复:结果,
JavaScript的数学是否被破坏?


我正在使用Math.round对数字进行四舍五入,并且由于某种原因,在末尾增加了不应该在那里的奇怪数字0。这里是我的代码:

$ $ p $ $ $ $ $ $ $返回Math.round($ digit * 1000)/ 1000;

我希望数字有3个小数点

例如:

  Math.round(29.469 * 1000)/ 1000 =返回该值:29.469000000000023 

似乎找不出原因。
是否有不同的方法将小数点四舍五入到某个小数点?我需要3个小数点。或者也许修剪后的第三个十进制数字?这将是完美的乘坐返回的数量和修剪第三位小数后的一切。


解决方案

  yourVariable (3).toFixed; 

会给你想要的东西。

MDN文档


Possible Duplicate:
Is JavaScript’s Math broken?

I'm using Math.round to round the number and for some reason it adds weird number of 0s at the end which should not be there. Here is my code:

return Math.round($digit * 1000) / 1000; 

i want numbers to have 3 decimal points

example:

  Math.round(29.469 * 1000) / 1000 = returns this value: 29.469000000000023 

cant seem to figure out why. is there a different way of rounding decimals to certain decimal point? i need 3 decimal points. Or maybe trim everything after third decimal digit? That would be perfect take the returned number and trim everything after third decimal.

解决方案

yourVariable.toFixed(3);

Will give you what you want.

MDN docs

这篇关于在JavaScript中使用Math.round会在最后添加奇怪的0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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