##### 标题：JavaScript数字

JavaScript的只有一种类型的数字.

## JavaScript中的数字

JavaScript 数字可以有也可以没有小数:

```var x = 34.00;    // A number with decimals
var y = 34;       // A number without decimals
```

```var x = 123e5;    // 12300000
var y = 123e-5;   // 0.00123
```

## JavaScript 数字总是64位浮点

JavaScript 数字总是存储为双精度浮点数, 按照国际IEEE 754标准.

Value (aka Fraction/Mantissa) Exponent Sign
52 bits (0 - 51)  11 bits (52 - 62) 1 bit (63)

## 精确度

```var x = 999999999999999;   // x will be 999999999999999
var y = 9999999999999999;  // y will be 10000000000000000
```

```var x = 0.2 + 0.1;         // x will be 0.30000000000000004
```

```var x = (0.2 * 10 + 0.1 * 10) / 10;       // x will be 0.3
```

## 十六进制

JavaScript 解读数字常量作为16进制，如果他们以0x开头.

```var x = 0xFF;             // x will be 255
```

```var myNumber = 128;
myNumber.toString(16);     // returns 80
myNumber.toString(8);      // returns 200
myNumber.toString(2);      // returns 10000000
```

## Infinity

```var myNumber = 2;
while (myNumber != Infinity) {          // Execute until Infinity
myNumber = myNumber * myNumber;
}
```

```var x =  2 / 0;          // x will be Infinity
var y = -2 / 0;          // y will be -Infinity
```

Infinity 是一个数字: Infinity的typeof返回number.

```typeof Infinity;        // returns "number"
```

## NaN - 不是一个数字

NaN是一个javascript的保留字，表示一个数不是一个合法的数.

```var x = 100 / "Apple";  // x will be NaN (Not a Number)
```

```var x = 100 / "10";     // x will be 10
```

```var x = 100 / "Apple";
isNaN(x);               // returns true because x is Not a Number
```

```var x = NaN;
var y = 5;
var z = x + y;         // z will be NaN
```

```var x = NaN;
var y = "5";
var z = x + y;         // z will be NaN5
```

NaN 是一个数字, typeof NaN 返回 number:

```typeof NaN;             // returns "number"
```

## 数字可以是对象

```var x = 123;
var y = new Number(123);

// typeof x 返回 number
// typeof y 返回 object
```

```var x = 500;
var y = new Number(500);

// (x == y) is true because x and y have equal values
```

```var x = 500;
var y = new Number(500);

// (x === y) is false because x and y have different types
```

```var x = new Number(500);
var y = new Number(500);

// (x == y) is false because objects cannot be compared
```