主题
Number 类型
介绍
number 用于任何类型的数字:整数或浮点数,范围是: -(2^{53}) 到 (2^{53}) 之间的数值。
js
let a = 123
let b = 12.345特殊数值
js
const a = Infinity // 正无穷大
const b = -Infinity // 负无穷大
const c = NaN // 非数字常见计算的坑
js
console.log(0.1 + 0.2) // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3) // false
console.log(Number(tue)) // 1
console.log(Number(false)) // 0
console.log(1 / 0) // Infinity
console.log(-1 / 0) // -Infinity
console.log('not a number' / 2) // NaN
console.log(NaN + 1) // NaN
console.log(3 * NaN) // NaN
console.log('not a number' / 2 - 1) // NaN进制转换
常见进制
- 十进制 (Decimal):42
- 二进制 (Binary):前缀
0b,例如:0b101010 - 八进制 (Octal):前缀
0o,例如:0o52 - 十六进制 (Hexadecimal):前缀
0x,例如:0x2a
数字 -> 进制字符串
js
let number = 42
let binaryString = number.toString(2)
console.log(binaryString) // "101010"
let octalString = number.toString(8)
console.log(octalString) // "52"
let decimalString = number.toString(10)
console.log(decimalString) // "42"
let hexString = number.toString(16)
console.log(hexString) // "2a"进制字符串 -> 数字
js
let binaryNumber = parseInt('101010', 2)
console.log(binaryNumber) // 42
let octalNumber = parseInt('52', 8)
console.log(octalNumber) // 42
let decimalNumber = parseInt('42', 10)
console.log(decimalNumber) // 42
let hexNumber = parseInt('2a', 16)
console.log(hexNumber) // 42