Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

console.log(0.1 + 0.2 == 0.3) // false
console.log(0.2 + 0.2 == 0.4)
console.log(0.1 + 0.3 == 0.4)
console.log(0.13 + 0.2 == 0.33)
console.log(0.3 + 0.4 == 0.7)
console.log(1.1 + 0.2 == 1.3)

我知道 0.1 + 0.2 = 0.30000000000000004 ,但想知道为什么。
问题分两层:1,为什么第一条输出false;2,为什么其他输出true。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
263 views
Welcome To Ask or Share your Answers For Others

1 Answer

假设十进制数字为整数10,在计算机中表示方式为 : 1010,二进制转换十进制的方法为:

1 * 2^3 + 0 * 2^2 + 1* 2^1 + 0* 2^0 = 10

即为:

8 + 0 + 2 + 0 = 10

那么小数的表示方法,假设10进制数为0.5,在计算机中表示为0.1,因为计算机只有0和1这两位,而换算方法为:

1 * 2^-1 = 0.5

同理可见计算机能表示的浮点数有哪些 :

    0.5 = 1 * 2^-1
    0.75 = 1 * 2^-1 +1 * 2^-2
    0.25 = 0 * 2^-1 +1 * 2^-2
    0.875 = 1 * 2^-1 +1 * 2^-2 + 1 * 2^-3
    0.9375 = 1 * 2^-1 +1 * 2^-2 + 1 * 2^-3 + 1 * 2^-4 

同理可见,0.2在计算机中表示为 :

 0.00110011000110...

后续位数你可以自己算,所以在计算机中0.2的表示方法只是一个无线接近于0.2的小数,但永远无法精确的表示出0.2,所以0.2 + 0.1 ≈ 0.3,而永远不会等于0.3


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...