如何处理 JavaScript 中的浮点数精度? [英] How to deal with floating point number precision in JavaScript?

查看:28
本文介绍了如何处理 JavaScript 中的浮点数精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下虚拟测试脚本:

function test() {无功x = 0.1 * 0.2;文档写(x);}test();

这将打印结果 0.020000000000000004 而它应该只打印 0.02(如果您使用计算器).据我了解,这是由于浮点乘法精度错误造成的.

有没有人有好的解决方案,以便在这种情况下我得到正确的结果 0.02?我知道有像 toFixed 这样的函数或者四舍五入是另一种可能性,但我真的想打印整数而不进行任何切割和四舍五入.只是想知道你们中的一个人是否有一些不错的、优雅的解决方案.

当然,否则我会四舍五入到大约 10 位数.

解决方案

来自浮点指南:

<块引用>

我该怎么做才能避免这个问题?

那要看什么样的你正在做的计算.

  • 如果您确实需要将结果准确相加,尤其是当您与金钱打交道:使用特殊的小数数据类型.
  • 如果您只是不想看到所有这些额外的小数位:只需格式化您的结果四舍五入为固定时的小数位数显示它.
  • 如果您没有可用的十进制数据类型,另一种方法是工作使用整数,例如做钱完全以美分计算.但这是更多的工作,有一些缺点.

请注意,第一点仅在您确实需要特定精确的十进制 行为时才适用.大多数人不需要那个,他们只是因为他们的程序不能正确处理像 1/10 这样的数字而感到恼火,却没有意识到如果 1/3 发生,他们甚至不会因为同样的错误而眨眼.

如果第一点确实适用于您,请使用 BigDecimal for JavaScript,一点也不优雅,但实际上解决了问题,而不是提供不完美的解决方法.

I have the following dummy test script:

function test() {
  var x = 0.1 * 0.2;
  document.write(x);
}
test();

This will print the result 0.020000000000000004 while it should just print 0.02 (if you use your calculator). As far as I understood this is due to errors in the floating point multiplication precision.

Does anyone have a good solution so that in such case I get the correct result 0.02? I know there are functions like toFixed or rounding would be another possibility, but I'd like to really have the whole number printed without any cutting and rounding. Just wanted to know if one of you has some nice, elegant solution.

Of course, otherwise I'll round to some 10 digits or so.

解决方案

From the Floating-Point Guide:

What can I do to avoid this problem?

That depends on what kind of calculations you’re doing.

  • If you really need your results to add up exactly, especially when you work with money: use a special decimal datatype.
  • If you just don’t want to see all those extra decimal places: simply format your result rounded to a fixed number of decimal places when displaying it.
  • If you have no decimal datatype available, an alternative is to work with integers, e.g. do money calculations entirely in cents. But this is more work and has some drawbacks.

Note that the first point only applies if you really need specific precise decimal behaviour. Most people don't need that, they're just irritated that their programs don't work correctly with numbers like 1/10 without realizing that they wouldn't even blink at the same error if it occurred with 1/3.

If the first point really applies to you, use BigDecimal for JavaScript, which is not elegant at all, but actually solves the problem rather than providing an imperfect workaround.

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

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