js interview 0.1+0.2!==0.3 reasons and solutions

problem causes

Because the bottom layer of js stores data in binary, decimal decimals are converted into binary as shown below
Insert image description here

Its calculation process is as follows: multiply the decimal by 2, then round to an integer, then obtain the decimal and continue to multiply by 2 to round up, and this cycle Insert image description herewill cause an infinite loop when converting decimal decimals to binary. In the case of infinite loops, it will automatically The redundant part is cut off and only 64 bits are stored. Therefore, decimal decimals are already "distorted" when stored at the bottom of the computer.

0.1+0.2When performing calculations, it is calculated according to the binary system, and the calculation result is converted into decimal system and presented to the client.
The value presented by the browser has a length limit, and any value that exceeds the length limit will be intercepted. The intercepted value is counted forward from the last decimal digit. If the following are all 0, they will not be retained. If they are not 0, they will not be retained. Yes, it will be retained.
Insert image description here

How to solve the accuracy problem?

  • Convert numbers to integers "expansion factor"
    console.log((0.1 * 10 + 0.2 * 10) / 10); //扩大系数,变为整数进行运算
    
  • Third-party libraries: Math.js, decimal.js, big.js…

Replenish

JS uses the Number type to represent numbers (integers and floating point numbers), following the IEEE-754 standard to represent a number through a 64-bit binary value
https://babbage.cs.qc.cuny.edu/IEEE-754.old/Decimal.html
Bit 0: sign bit, 0 represents a positive number, 1 represents a negative number S
1st to 11th digit "11-bit exponent": stores the exponent part E
12th to 63rd digit "52-bit mantissa": stores the decimal part ( That is, significant figures) F
Note: The first digit of the mantissa defaults to 1 in the reduced form (omitted and not written)

Guess you like

Origin blog.csdn.net/weixin_44157964/article/details/119065239