Background:

In my work, I encountered this kind of addition operation. At the beginning, I didn’t notice the reason for this problem, and I really couldn’t figure out where so many zeros in the back came from.

The reasons are as follows:

  • This is true not only for JavaScript, but for all languages that follow the IEEE 754 specification;
  • In JavaScript, all numbers are stored as 64-bit double-precision floating-point numbers;
  • A double floating-point number is divided into three segments on the 64bit, and these three segments determine the value of a floating point number. The 64-bit division is “1-11-52” mode, specifically:
    • 1. The highest bit (the leftmost bit) represents the sign bit, 0 represents positive, 1 represents negative;
    • 2.11 digit indicates the index part;
    • 3.52 bits represent the mantissa part, that is, the effective domain part

I don’t really understand it, but I do understand how this javascript is stored.

The following is a function to solve the problem of adding floating point numbers:

function add() {
    const args = [...arguments]
    const maxLen = Math.max.apply(
    null,
    args.map(item => {
    const str = String(item).split('. ') [1]return str ? str.length : 0
    })
    )
    return (
    args.reduce((sum, cur) => sum + cur * 10 ** maxLen, 0) / 10 ** maxLen
    )
  }Copy the code

Conclusion: there will always be a lot of anomalies in JS, according to different situations to analyze the specific situation, but ultimately are inseparable from the js foundation, more understanding of some JS development foundation, the later development of the pit filling speed will be faster

Forgive links: why is 0.1+0.2 equal to 0.30000000000000004, how to solve this problem in code?