JavaScript 中的乘法 int 和 float(double)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16608146/
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-27 05:19:38  来源:igfitidea点击:

Multiplication int and float(double) in JavaScript

javascript

提问by Afsun Khammadli

I want to make multiplication using JavaScript.

我想使用JavaScript.

Multiplication of 2 and 0.15 is 0.3 but 3 and 0.15 is 0.44999999999999996. I want to get 0.45 such as result. How can I do it with JavaScript?

2 和 0.15 的乘积是 0.3,但 3 和 0.15 的乘积是 0.44999999999999996。我想得到 0.45 这样的结果。我该怎么做JavaScript?

回答by Simon M

It's a rounding error. You may want to round your number to a fixed amount of digits, like this:

这是一个舍入错误。您可能希望将您的数字四舍五入为固定数量的数字,如下所示:

parseFloat((your_number).toFixed(2));

回答by Bathsheba

Unfortunately this happens in any language using floating point arithmetic. It's an artifact arising when floating point operations are encoded into binary, operations performed, and decoded from binary to report the answer in a form you'd expect.

不幸的是,这在任何使用浮点运算的语言中都会发生。这是当浮点运算被编码为二进制、执行运算并从二进制解码以以您期望的形式报告答案时出现的工件。

Depending on what you want to do with the output, you can call a round()-like function to round to a number of decimal places or compare the output to a value using a (small) number called a tolerance. E.g. two numbers are considered equal if their absolute difference is less than this tolerance.

根据您要对输出执行的操作,您可以调用类似 round() 的函数来四舍五入到小数位数,或者使用称为tolerance的(小)数字将输出与值进行比较。例如,如果两个数字的绝对差小于此容差,则认为它们相等。