处理 Javascript 中的浮点精度 [英] Dealing with float precision in Javascript

查看:21
本文介绍了处理 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中如何处理浮点数精度?

你有几个选择:

  • 对小数使用特殊的数据类型,例如 decimal.js
  • 将您的结果格式化为一些固定数量的有效数字,如下所示:(Math.floor(y/x) * x).toFixed(2)
  • 将所有数字转换为整数

这篇关于处理 Javascript 中的浮点精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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