javascript javascript中的十进制减法问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10713878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:47:43  来源:igfitidea点击:

Decimal Subtraction problems in javascript

javascript

提问by crystal

Possible Duplicate:
Is JavaScript's Math broken?

可能的重复:
JavaScript 的数学有问题吗?

when i subtract 6.4-1.6 i am getting the answer as 4.800000000000001 in JS, but i need as 4.8 without using toFixed(), toPrecision() and Math.round(). any idea???

当我减去 6.4-1.6 时,我在 JS 中得到的答案是 4.800000000000001,但我需要 4.8 而不使用 toFixed()、toPrecision() 和 Math.round()。任何的想法???

Thanks,

谢谢,

crystal

水晶

回答by Mark

Convert to integers before doing the subtraction to avoid problems with floating point arithmetic:

在做减法之前转换为整数以避免浮点运算问题:

(6.4 * 10 - 1.6 * 10) / 10

See What Every Programmer Should Know About Floating-Point Arithmetic

了解每个程序员应该了解的关于浮点运算的知识

回答by apsillers

This is a well-known limitationof IEEE 754 floating point numbers. See How to deal with floating point number precision in JavaScript?for solutions.

这是众所周知的 IEEE 754 浮点数限制。请参阅如何处理 JavaScript 中的浮点数精度?为解决方案。