Javascript 如何在Javascript中乘法?小数的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14490496/
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
How to multiply in Javascript? problems with decimals
提问by gustavomanolo
i've the following code in Javascript:
我在 Javascript 中有以下代码:
var m1 = 2232.00;
var percent = (10/100);
var total = percent*m1;
alert(total);
The problem is that the variable "total" gives me "223.20000000000002" and it should be "223.2", what should i do to get the correct value?
问题是变量“total”给了我“223.20000000000002”,它应该是“223.2”,我应该怎么做才能得到正确的值?
回答by Malik Khalil
.toFixed()is best solution.It will keep only two digits after dot.
.toFixed()是最好的解决方案。它只会保留点后的两位数。
Exp 1:
经验 1:
var value = 3.666;
value.toFixed(2); //Output : 3.67
Exp 2:
经验 2:
var value = 3.0000;
value.toFixed(2); //Output : 3.00
回答by Niet the Dark Absol
You can't get the exact value. This is the fundamental problem with floating-point numbers.
您无法获得确切的值。这是浮点数的基本问题。
You can force a fixed number of decimal numbers with toFixed:
您可以强制使用固定数量的十进制数toFixed:
alert(total.toFixed(2));
However, keep in mind that this will leave trailing zeroes, which you might not want. You can remove them with .replace(/0+$/,'');
但是,请记住,这会留下您可能不想要的尾随零。你可以删除它们.replace(/0+$/,'');
回答by WildCrustacean
If you are trying to display this number, you could convert to a string with toFixed(1). If you do this, keep track of the types because you can't then multiply the string with another number.
如果您尝试显示此数字,您可以使用toFixed(1)转换为字符串。如果您这样做,请跟踪类型,因为您无法将字符串与另一个数字相乘。
If you are going to use it in another computation you could truncate it to one decimal place:
如果您打算在另一个计算中使用它,您可以将其截断到一位小数:
Math.round( total * 10 ) / 10
However, as pointed out by various people, the inexact value is just the way floating point numbers are.
然而,正如许多人所指出的,不精确的值就是浮点数的方式。
See the questions linked in the comments for more good information.
请参阅评论中链接的问题以获取更多有用的信息。
回答by DrWaky
The operator "*" and "/" do not work perfectly always, for example:
运算符“*”和“/”并不总是完美地工作,例如:
32.09 * 100 = 3209.0000000000005
100 / (1 / 32.09) = 3209.0000000000005
Solution:
解决方案:
One solution, the easy one, to have decimals is useing .toFixed(2) where "2" is the number of decimal digits that you want. But you have to take into account this return you a String, and it rounds the value.
一种解决方案,最简单的方法是使用 .toFixed(2) ,其中“2”是您想要的小数位数。但是您必须考虑到这会返回一个字符串,并且它会舍入该值。
45.6789.toFixed(2) —> "45.68" as String
Other option, the most complete, is using .toLocaleString that converts the number properly to the country code that you want. You can set a pair of params to fix the decimals values always to 2. This also returns you a String:
其他选项,最完整的是使用 .toLocaleString 将数字正确转换为您想要的国家/地区代码。您可以设置一对参数以将小数值始终固定为 2。这也会返回一个字符串:
(654.3453).toLocaleString(
'en-US',
{minimumFractionDigits: 2, maximumFractionDigits: 2},
) —> "654.35" as String
If you need it as a Number, you can wrap it into Number( ... ) :
如果你需要它作为一个数字,你可以把它包装成 Number( ... ) :
Number((654.3453).toLocaleString(
'en-US',
{minimumFractionDigits: 2, maximumFractionDigits: 2},
)) —> 654.35 as Number
If you only want a no decimal number, use one of this methods to be sure that the result is without decimals.
如果您只想要一个没有小数的数字,请使用其中一种方法来确保结果没有小数。
Math.trunc(32.09); —> 32 as Number
(32.09).toFixed(0); —> “32” as String
32.09 | 0; —> 32 as Number
回答by gustavomanolo
I found the answer using the following pages, thanks to Dimitry:
感谢Dimitry,我使用以下页面找到了答案:
Floating-point cheat sheet for JavaScript
I decided to use the following clases because i need the exact values of the operations and they're related to money operations:
我决定使用以下类,因为我需要操作的确切值,并且它们与货币操作有关:
回答by Kevin Leary
This can be done well with an external library called decimal.jsthat provides a Decimaltype for JavaScript. It's also available for Node on npm. Below is an example that replicates the original example from gustavomanolousing decimal.js.
这可以通过名为decimal.js的外部库来很好地完成,该库Decimal为JavaScript提供了一种类型。它也可用于 npm 上的 Node。下面是一个使用decimal.js从gustavomanolo复制原始示例的示例。
// Decimal type provided by decimal.js (http://mikemcl.github.io/decimal.js/)
var m1 = new Decimal( 2232.00 );
var percent = new Decimal( 10/100 );
var total = m1.mul(percent);
console.log( 'Total:', total );
<script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/7.2.3/decimal.min.js"></script>
回答by PetrosM
Here is a work around solution for multiplication of floating numbers. It's pretty simple but works for me. You figure out how many decimals the numbers have with this function.
这是一个解决浮点数乘法的解决方案。这很简单,但对我有用。您可以使用此函数计算数字的小数位数。
function decimalPlaces(num) {
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(
0,
// Number of digits right of decimal point.
(match[1] ? match[1].length : 0)
// Adjust for scientific notation.
- (match[2] ? +match[2] : 0));
}
And then for your final answer "total" you do
然后对于您的最终答案“总计”,您会这样做
total = total.toFixed(decimalPlaces(a)+decimalPlaces(b));
where a,b are your numbers
其中 a,b 是您的数字
回答by srijan
total.toFixed(2)may help. But note that the totalvariable be will typecasted into a string.
total.toFixed(2)可能有帮助。但请注意,total变量 be 将被类型转换为字符串。
回答by rubens21
Just try
你试一试
var x = 0.07;
console.log((x+1)*100 - 100);
now, replace the value of x for the other values ;-)
现在,将 x 的值替换为其他值;-)
回答by Erik123
I ended up with the following solution:
我最终得到了以下解决方案:
function decimalmultiply(a, b) {
return parseFloat((a * b).toFixed(12));
}
10.50*30.45=319.72499999999997
decimalmultiply(10.50,30.45)=319.725
This method returns a number, not a string, without truncating significant decimals (up to 12).
此方法返回一个number,而不是一个string,而不会截断有效的小数(最多 12 个)。

