简体   繁体   English

如何在JavaScript中计算小数

[英]How decimals are calculated in javascript

I have to do some calculation in decimals in my application using javascript but the result is unexpected. 我必须使用javascript在我的应用程序中进行一些计算,但结果出乎意料。

The result of the below statement is 1.707 [as expected] 以下语句的结果为1.707 [按预期]

var total=1.17+0.237+0.3;

also when we add the numbers below, I am getting 0.7070000000000001 [unexpected] 当我们加上下面的数字时,我得到0.7070000000000001 [意外]

var totalnew=0.17+0.237+0.3;

Also, the expression (0.1+0.2===0.3) returns false[unexpected], but (1.1+0.2===1.3) returns true[as expected] . 另外,表达式(0.1 + 0.2 === 0.3)返回false [意外],但是(1.1 + 0.2 === 1.3)返回true [符合预期]。 Why is this happening and what is the workaround for this. 为什么会发生这种情况以及解决方法是什么?

Floating point is notoriously tricky. 浮点是非常棘手的。 Basically it boils down to that there are an infinite amount of values between two real numbers, so it is impossible to represent them correctly in a computer. 基本上可以归结为两个实数之间存在无限数量的值,因此不可能在计算机中正确表示它们。

If you want to print the number i suggest: 如果要打印号码,我建议:

total.toFixed();

Which will always give you three decimal places. 它将始终为您提供三个小数位。 And when you want to check if two floats are the same you need to do something like this: 当您要检查两个浮点数是否相同时,您需要执行以下操作:

function nearlyEqual(a, b, epsilon) {
    var absA = Math.abs(a);
    var absB = Math.abs(b);
    var diff = Math.abs(a - b);
    var minNormal = 1.1754943508222875e-38;

    if (a == b) { // shortcut, handles infinities
        return true;
    } else if (a == 0 || b == 0 || diff < minNormal) {
        // a or b is zero or both are extremely close to it
        // relative error is less meaningful here
        return diff < (epsilon * minNormal);
    } else { // use relative error
        return diff / (absA + absB) < epsilon;
    }
}

nearlyEqual(0.1+0.2, 0.3, 0.0001);

As is suggested here How should I do floating point comparison? 如此处建议的, 我应该如何进行浮点比较?

This is because the values have no fixed precision. 这是因为值没有固定的精度。 To resolve this, try implementing Math.Round. 若要解决此问题,请尝试实现Math.Round。

Math.round((0.17 + 0.237 + 0.3) * 1e12) / 1e12

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM