在Javascript中处理浮动精度 [英] Dealing with float precision in Javascript
本文介绍了在Javascript中处理浮动精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在javascript中有大量的数值 y
。我想通过将它们舍入到最接近的 x
的倍数来进行分组,并将结果转换为字符串。
I have a large amount of numeric values y
in javascript. I want to group them by rounding them down to the nearest multiple of x
and convert the result to a string.
如何解决烦人的浮点精度?
How do I get around the annoying floating point precision?
例如:
0.2 + 0.4 = 0.6000000000000001
我尝试过的两件事:
>>> y = 1.23456789
>>> x = 0.2
>>> parseInt(Math.round(Math.floor(y/x))) * x;
1.2000000000000002
和:
>>> y = 1.23456789
>>> x = 0.2
>>> y - (y % x)
1.2000000000000002
推荐答案
从这篇文章:如何处理JavaScript中的浮点数精度?
您有几个选择:
- 数据类型为小数,例如 BigDecimal
- 格式化您的结果到一些固定数量的有效数字,像这样:
(Math.floor(y / x)* x).toFixed(2)
- 将所有数字转换为整数
这篇关于在Javascript中处理浮动精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文