JavaScript笔记(三)

  |   Javascript 前端

3.1.4 Binary Floating-Point and Rounding Errors

There are infinitely many real numbers, but only a finite number of them (18437736874454810627, to be exact) can be represented exactly by the JavaScript floating-point format. This means that when you’re working with real numbers in JavaScript, the representation of the number will often be an approximation of the actual number.

var x = .3 - .2;  // thirty cents minus 20 cents
var y = .2 - .1;  // twenty cents minus 10 cents
x == y            // => false: the two values are not the same!
x == .1           // => false: .3-.2 is not equal to .1
y == .1           // => true: .2-.1 is equal to .1

3.1.4 二进制浮点数和四舍五入错误

实数有无数个,但JavaScript通过浮点数的形式只能表示其中有限的个数(确切地说是18437736874454810627个)。也就是说,当在JavaScript中使用实数的时候,常常只是真实值的一个近似表示。

var x = .3 - .2;  // 30美分减去20美分
var y = .2 - .1;  // 20美分减去10美分
x == y            // => false: 两值不相等!
x == .1           // => false: .3-.2 不等于 .1
y == .1           // => true: .2-.1 is 等于 .1

来源:《JavaScript权威指南》--3.1.4 二进制浮点数和四舍五入错误 37页-38页