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

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

问题描述

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

这会打印结果 0.020000000000000004 应该打印 0.02 (如果您使用计算器)。据我所知,这是由于在浮点乘法精度错误。

有没有人有一个很好的解决方案,以便在这种情况下,我得到正确的结果 0.02 ?我知道有一些函数像 toFixed 或舍入是另一种可能性,但是我希望真正将整个数字打印出来而没有任何切割和舍入。只是想知道,如果你们中的一个人有一些不错的,优雅的解决方案。



当然,否则我会舍去大约10个数字左右。 b $ b

解决方案

浮点指南


我能做些什么来避免这个问题?

b

这取决于你正在做什么样的
计算。


  • 如果你真的需要你的结果准确地加起来,特别是当你
    使用money时:使用特殊的十进制
    datatype。
  • 如果你不想看到所有的额外的小数位:只要
    格式化您的结果,当
    显示时,您的结果四舍五入到固定的
    小数位数。

  • 如果没有可用的小数数据类型,另一种方法是用整数工作
    ,例如以美分完成
    的计算。但
    这是更多的工作,并有一些
    的缺点。

第一点只适用于你确实需要特定的十进制 行为。大多数人不需要这样,他们只是激怒了他们的程序不能正确地使用像1/10这样的数字,而没有意识到,如果它以1/3出现,他们甚至不会眨眼相同的错误。 p>

如果第一个点适用于您,请使用 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天全站免登陆