Javascript Javascript浮点减法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6027937/
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
Javascript float subtract
提问by Teneff
I was wondering how can I subtract two negative Floating-Point numbers in javascript. I tried:
我想知道如何在 javascript 中减去两个负浮点数。我试过:
alert(-0.2-0.1);
and the result is -0.30000000000000004
. Am I doing something wrong? What do I have to do to get -0.3
?
结果是-0.30000000000000004
。难道我做错了什么?我该怎么做才能得到-0.3
?
回答by Alberto Zaccagni
No, nothing wrong with your code, most decimal fractions cannot be represented exactly in binary, use
不,你的代码没有问题,大多数十进制小数不能用二进制精确表示,使用
number.toFixed(x)
Where x
is the number of decimals you want and number
is the result of the subtraction.
哪里x
是你想要的小数位数,number
是减法的结果。
回答by Fabrizio D'Ammassa
The reason of your problem is explained here: Why does modulus operator return fractional number in javascript?
您的问题的原因在这里解释: 为什么模数运算符在javascript中返回小数?
A possible solution could be:
一个可能的解决方案可能是:
<script type="text/javascript">
var result = (-20-10)/100;
alert("My result is "+result);
</script>
回答by daalbert
You are doing nothing wrong, what you are seeing is the side effect of computers storing numbers in base 2. In base 10, 1/3 can't be precisely represented: .33333333 (with a bar over the 3). The same is true for 1/10 and 1/5 in base 2 or binary. The answer you see is merely the result of a rounding error. If you are working with money, it is often advised to just store values as cents to avoid some floating point errors.
您没有做错任何事情,您看到的是计算机以 2 为基数存储数字的副作用。在以 10 为基数的情况下,无法精确表示 1/3:.33333333(在 3 上有一个横杠)。对于基数为 2 或二进制的 1/10 和 1/5 也是如此。您看到的答案仅仅是舍入误差的结果。如果您正在处理金钱,通常建议将值存储为美分以避免出现一些浮点错误。
As far as fixing the result you can do something like:
至于修复结果,您可以执行以下操作:
var SIGDIG= 100000000;
alert( Math.floor((-0.2-0.1)*SIGDIG)/SIGDIG );
回答by Cristian Douce
Another possible solution might be this:
另一种可能的解决方案可能是这样的:
Number((-0.2-0.1).toFixed(x))
Where x should be the tolerance in decimals you'd like.
其中 x 应该是您想要的小数公差。
Running this with an x
of 16, gives me an output of -0.3
.
x
以 16 的值运行它,给我的输出为-0.3
.
-0.3 === Number((-0.2-0.1).toFixed(16)) // true, and also with every 0 < x < 16
Let me know.
让我知道。
回答by sgokhales
toFixed()
is what you must be looking for.
toFixed()
是您必须寻找的。
E.g
例如
number.toFixed(x);
where x is the number of digits after the decimal point. It is optional with default value of 0.
其中 x 是小数点后的位数。它是可选的,默认值为 0。
More here : Javascript Number.toFixed() Method