Introduction to the
Because JS uses IEEE 754 double precision version (64-bit), and as long as the IEEE 754 language has this problem. Those of you who have studied the principle of computer composition should know that the data in our computer is composed of 0 and 1, and the js numbers in the computer are also composed of 0 and 1. Let’s talk first about how decimals can be converted to binary.
// 0.125 decimal -> binary 0.125 * 2 = 0.25 = 0 0.5 * 2 = 0 0.5 * 2 = 1Copy the code
To determine whether to take a binary bit 0 or 1, multiply the decimal part by 2.
- If the decimal number is smaller than 1, go to step 2. If the decimal number is larger than 1, go to Step 3. If the decimal number is larger than 1, go to Step 4.
- 2. If the decimal part multiplied by 2 does not exceed 1, the binary part is 0, and return to Step 1
- 3. If multiplied by 2 and more than 1, take 1 and do not use the number to the left of the decimal point to keep the number to the right of the decimal point. Take 1 to return to step 1
- 4. If the decimal multiplied by 2 equals exactly 1, the conversion ends and the binary is 1
If it’s not clear from the top you can go down
0.1 decimal -> binary 0.1 * 2 = 0.2 0 0.2 * 2 = 0.4 0 0.4 * 2 = 0.8 0 0.8 * 2 = 1.6 1 0.6 * 2 = 1.2 1 0.2 * 2 = 0.4 0 0.4 * 2 = 0.8 take 0 0.8 * 2 = 1.6 take 1 0.6 * 2 = 1.2 take 1 //0.000110011(0011) '0.1 binary (0011) inside the numbers represent the cycleCopy the code
You’ll notice that switching from 0.1 to 2 will loop wirelessly forever, and you won’t be able to calculate a correct binary number. So we get 0.1 = 0.000110011(0011), then the calculation of 0.2 is basically as shown above, so we get 0.2 = 0.00110011(0011). One of the 64 sign bits, eleven integer bits, and fifty-two decimal bits. Since 0.1 and 0.2 are both infinitesimal cycles, the end of the decimal place needs to be checked for carrying (like rounding decimal places), so adding the two bits together gives 0.010011…. 0100, which in decimal form is 0.30000000000000004
summary
ParseFloat ((0.1 +0.2).tofixed (10))Copy the code
The following is a recommendation of a small tool specifically used to deal with js floating point number addition and subtraction problems you can go to see
Github.com/dykily/easy…
Give a star if you think it’s useful