Home  >  Article  >  Web Front-end  >  Detailed explanation of js floating point calculation problems

Detailed explanation of js floating point calculation problems

零下一度
零下一度Original
2017-06-30 10:18:091378browse

Analysis

JavaScript has only one number type Number, and all numbers in Javascript are expressed in the IEEE-754 standard format. The precision problem of floating point numbers is not unique to JavaScript, because some decimals have infinite digits when expressed in binary:

0.1              0.0001100110011001100110011001100110011001100110011001101
0.2              0.001100110011001100110011001100110011001100110011001101
0.3              0.010011001100110011001100110011001100110011001100110011
0.5              0.1
0.6              0.10011001100110011001100110011001100110011001100110011

So for example 1.1, the program actually cannot It really represents '1.1', but it can only be accurate to a certain extent. This is an inevitable loss of precision:

1.09999999999999999

In JavaScript, the problem is more complicated, here is just Give some test data in Chrome:

 输入               输出1.0-0.9 == 0.1     False1.0-0.8 == 0.2     False1.0-0.7 == 0.3     False1.0-0.6 == 0.4     True1.0-0.5 == 0.5     True1.0-0.4 == 0.6     True1.0-0.3 == 0.7     True1.0-0.2 == 0.8     True1.0-0.1 == 0.9     True

Solution

So how to avoid this type of ` 1.0-0.9 != 0.1 ` non-bug type problems? The following is a commonly used solution. The calculation result is reduced in precision before judging the floating point operation result, because the precision reduction process will always be automatically rounded:

(1.0-0.9).toFixed(digits)     // toFixed() 精度参数须在 0 与20 之间(1.0-0.9).toFixed(10)== 0.1   // 结果为True(1.0-0.8).toFixed(10)== 0.2   // 结果为True(1.0-0.7).toFixed(10)== 0.3   // 结果为True(11.0-11.8).toFixed(10) == -0.8   // 结果为TrueparseFloat((1.0-0.9).toFixed(10)) === 0.1   // 结果为TrueparseFloat((1.0-0.8).toFixed(10)) === 0.2   // 结果为TrueparseFloat((1.0-0.7).toFixed(10)) === 0.3   // 结果为TrueparseFloat((11.0-11.8).toFixed(10)) === -0.8   // 结果为True

Method refining

// 通过isEqual工具方法判断数值是否相等function isEqual(number1, number2, digits){
    digits = digits || 10; // 默认精度为10return number1.toFixed(digits) === number2.toFixed(digits);
}

isEqual(1.0-0.7, 0.3);  // return true// 原生扩展方式,更喜欢面向对象的风格Number.prototype.isEqual = function(number, digits){
    digits = digits || 10; // 默认精度为10return this.toFixed(digits) === number.toFixed(digits);
}

(1.0-0.7).isEqual(0.3); // return true

<br>

The above is the detailed content of Detailed explanation of js floating point calculation problems. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn