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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:56:37  来源:igfitidea点击:

Javascript float subtract

javascriptfloating-point

提问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 xis the number of decimals you want and numberis 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 xof 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

更多信息:Javascript Number.toFixed() 方法