gpt4 book ai didi

javascript - JavaScript中如何处理 float 精度?

转载 作者:行者123 更新时间:2023-11-28 08:22:27 26 4
gpt4 key购买 nike

我有以下虚拟测试脚本:

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

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

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

当然,否则我会四舍五入到大约 10 位数字左右。

最佳答案

来自Floating-Point Guide :

What can I do to avoid this problem?

That depends on what kind ofcalculations you’re doing.

  • If you really need your results to add up exactly, especially when youwork with money: use a special decimaldatatype.
  • If you just don’t want to see all those extra decimal places: simplyformat your result rounded to a fixednumber of decimal places whendisplaying it.
  • If you have no decimal datatype available, an alternative is to workwith integers, e.g. do moneycalculations entirely in cents. Butthis is more work and has somedrawbacks.

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

如果第一点确实适用于您,请使用 BigDecimal for JavaScriptDecimalJS ,它实际上解决了问题,而不是提供不完美的解决方法。

关于javascript - JavaScript中如何处理 float 精度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22810225/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com