数值扩展
(1) Number.EPSILON
Number.EPSILON 是 JavaScript 表示的最小精度
EPSILON 属性的值接近于 2.2204460492503130808472633361816E-16
1 2 3 4 5 6 7 8 9 10 11 12 13
|
console.log(0.1 + 0.2); console.log(0.1 + 0.2 === 0.3);
function equal(a, b){ if(Math.abs(a - b) < Number.EPSILON){ return true; }else{ return false; } } console.log(equal(0.1 + 0.2, 0.3));
|
(2) 数字进制
ES6 提供了二进制和八进制数值的新的写法,分别用前缀 0b
和 0o
表示
1 2 3 4 5 6 7 8 9
|
let b = 0b1010;
let o = 0o777;
let d = 100;
let x = 0xff;
|
(3) Number.isFinite()
Number.isFinite() 用来检查一个数值是否为有限的
1 2 3 4 5 6 7
| console.log(Number.isFinite(100)); console.log(Number.isFinite(100/0)); console.log(Number.isFinite(Infinity)); console.log(Number.isFinite(1/3)); console.log(Number.isFinite(0.3)); console.log(Number.isFinite(0.1 + 0.2));
|
(4) Number.isNaN()
Number.isNaN() 用来检查一个值是否为 NaN
Number.isNaN('abc')
返回 false
,isNaN('abc')
返回 true
,其他情况下 Number.isNaN()
和 isNaN()
相同
1 2 3 4 5 6
| console.log(Number.isNaN(123)); console.log(Number.isNaN('123')); console.log(Number.isNaN('abc')); console.log(Number.isNaN(3/'b')); console.log(Number.isNaN(Number.parseInt('abc')));
|
(5) Number.parseInt() 和 Number.parseFloat()
ES6 将全局方法 parseInt 和 parseFloat,移植到 Number 对象上面,使用不变
Number.parseInt()
和 parseInt()
结果相同
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| console.log(Number.parseInt('100')); console.log(Number.parseFloat('3.14')); console.log(Number.parseInt('abc')); console.log(Number.parseFloat('abc')); console.log(Number.parseInt('120letter')); console.log(Number.parseFloat('1.414character')); console.log(Number.parseInt('letter120')); console.log(Number.parseFloat('character1.414')); console.log(Number.parseInt('10abc20')); console.log(Number.parseFloat('1.23abc456')); console.log(Number.parseInt('num120abc')); console.log(Number.parseFloat('char1.414abc')); console.log(Number.parseInt('')); console.log(Number.parseFloat(''));
|
(6) Number.isInteger()
Number.isInteger()
用来判断一个数值是否为整数
1 2 3 4 5 6 7
| console.log(Number.isInteger(5)); console.log(Number.isInteger(2.5)); console.log(Number.isInteger('5')); console.log(Number.isInteger('2.5')); console.log(Number.isInteger('abc')); console.log(Number.isInteger('2.5abc'));
|
(7) Math.trunc()
Math.trunc() 用于去除一个数的小数部分,返回整数部分
1 2 3 4 5
| console.log(Math.trunc(3.5)); console.log(Math.trunc('3.5')); console.log(Math.trunc('abc')); console.log(Math.trunc('2.5abc'));
|
(8) Math.sign()
Math.sign()
判断一个数到底为正数 负数 还是零
1 2 3 4 5 6 7 8 9 10
| console.log(Math.sign(100)); console.log(Math.sign(0)); console.log(Math.sign(-20000)); console.log(Math.sign('100')); console.log(Math.sign('0')); console.log(Math.sign('-20000')); console.log(Math.sign('a100')); console.log(Math.sign('0b')); console.log(Math.sign('a-20000b'));
|