Preface
Hello, everyone, I am Lin Sanxin, 161bfe3acefa42 uses the most easy-to-understand words to is my motto, is the prerequisite for advanced is my original intention. There is a problem that bothers the majority of front-end engineers, that is 0.1 + 0.2 !== 0.3
As you may all know, this is because the computer stores the numbers through binary, and when presented, it stores them through
decimal, so there is an error. But continue to ask you why the computer's
binary storage will cause errors, you may be hesitating. . .
Decimal to Binary
Let's first talk about how to convert decimal to binary. . There are three situations:
- 1. Integer
- 2. Negative integer
- 3. Decimal
Integer
How is the integer conversion from decimal to binary? Remember a formula: divides by two and takes the remainder, and then arranges in reverse order, with the high order zero . What do you mean? Don't worry, let me tell you about it. Let me take 81
as an example. After all, there was once a man who scored 81 points in a single game:
We can get 1000101
, it can be seen that there are 7 bits, but the internal representation of the computer is fixed-length, such as 8-bit, 16-bit, 32-bit, so 7-bit is not enough, you need to add 0 to the high
, that is
01000101
, the specification is (81)10 = (01000101)
Negative integer
For negative integers, the rules are as follows:
- Step 1: Convert a positive integer to binary
- Step 2: Invert the binary
- Step 3: Add 1 to the inverted binary
Decimal
Converting a decimal to binary is like this: Multiply the number after the decimal point by 2 to get the result, take the integer part of the result (either 0 or 1), and then multiply the number after the decimal point by 2 to get the result. Then take the integer part of the result, and then multiply the number after the decimal point of the result by 2. . . . And so on. . Know that the decimal part is 0 or the number of digits has reached the number of digits. Then arrange the integers taken in this process in order.
Let me give you an example, such as 0.125
:
Let me give another example, such as 121.6
:
0.1 + 0.2
Back to 0.1 + 0.2
this question
It can be seen that the conversion of 0.1 and 0.2 into binary is an infinite loop, exceeding 52 bits, so when storing, only approximate values can be used to store them. Naturally, when
0.1 + 0.2
, the approximate value converted to decimal is definitely an approximate value, so Cause errors
Concluding remarks
I am Lin Sanxin, an enthusiastic front-end rookie programmer. If you are motivated, like the front-end, and want to learn the front-end, then we can make friends and fish together haha, fish school
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。