toFixed(2)将"x.525"取整.不一致? [英] toFixed(2) rounds "x.525" inconsistently?

查看:35
本文介绍了toFixed(2)将"x.525"取整.不一致?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用toFixed时出现舍入错误:

I'm experiencing rounding errors when using toFixed:

我在数值计算中使用了 toFixed(2),但是在少数情况下,四舍五入的结果与预期不符.

I used toFixed(2) on my numeric value calculations, but the rounding results are not as expected for few cases.

假设将 toFixed(2)应用于值 17.525 ,则得出结果 17.52 ,如果将其应用于> 5.525 ,然后得出结果 5.53 .

Suppose that toFixed(2) is applied for value 17.525 then it gives the result 17.52, And if it is applied for 5.525 then it gives the result 5.53.

在后一种情况下,四舍五入的结果是准确的,因此,如在后一种情况下,您可以建议需要做些什么才能获得准确的四舍五入结果.还是可以建议使用此toFixed函数的替代方法以获得正确的舍入结果?

In the later case the rounding result is accurate, so can you please suggest what needs to be done to get the accurate rounding result as in the later case. Or can you please suggest an alternative to this toFixed function to get correct rounding results?

推荐答案

浮点数不正确意味着大多数以.525结尾的数字实际上是.52500..1,而其他数字是.5249999 .....

Floating point inaccuracy means that most numbers ending .525 are actually .52500..1, and others are .5249999.....

取值的哪种方式取决于IEEE-754浮点中最接近的实际表示形式是高于还是低于期望值.

Which way the value rounds depends on whether the closest actual representation in IEEE-754 floating point is above or below the desired value.

这篇关于toFixed(2)将"x.525"取整.不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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