Markdown

[ES6]Number

CH6 Number

Properties

Number.EPSILON

The smallest interval between two representable numbers.
var result = Math.abs(0.2 - 0.3 + 0.1);

console.log(result);
// expected output: 2.7755575615628914e-17

console.log(result < Number.EPSILON);
// expected output: true

Number.MAX_SAFE_INTEGER

The maximum safe integer in JavaScript (253 - 1).
var x = Number.MAX_SAFE_INTEGER + 1;
var y = Number.MAX_SAFE_INTEGER + 2;

console.log(Number.MAX_SAFE_INTEGER);
// expected output: 9007199254740991

console.log(x);
// expected output: 9007199254740992

console.log(x === y);
// expected output: true

Number.MAX_SAFE_INTEGER // 9007199254740991
Math.pow(2, 53) - 1     // 9007199254740991

Number.MAX_VALUE

The largest positive representable number.
function multiply(x, y) {
  if (x * y > Number.MAX_VALUE) {
    return ("Process as Infinity");
  }
  return (x * y);
}

console.log(multiply(1.7976931348623157e+308, 1));
// expected output: 1.7976931348623157e+308

console.log(multiply(1.7976931348623157e+308, 2));
// expected output: "Process as Infinity"

Number.MIN_SAFE_INTEGER

The minimum safe integer in JavaScript (-(253 - 1)).
var x = Number.MIN_SAFE_INTEGER - 1;
var y = Number.MIN_SAFE_INTEGER - 2;

console.log(Number.MIN_SAFE_INTEGER);
// expected output: -9007199254740991

console.log(x);
// expected output: -9007199254740992

console.log(x === y);
// expected output: true

Number.MIN_VALUE

The smallest positive representable number - that is, the positive number closest to zero (without actually being zero).
function multiply(x, y) {
  if (x * y < Number.MIN_VALUE) {
    return "Process as -Infinity";
  }
  return (x * y);
}

console.log(multiply(5e-324, 1));
// expected output: 5e-324

console.log(multiply(-1.7976931348623157e+308, 2));
// expected output: Process as -Infinity

Number.NaN

Special “not a number” value.
function clean(x) {
  if (x === Number.NaN) {
    // can never be true
    return null;
  }
  if (isNaN(x)) {
    return 0;
  }
}

console.log(clean(Number.NaN));
// expected output: 0

Number.NEGATIVE_INFINITY

Special value representing negative infinity; returned on overflow.
function checkNumber(smallNumber) {
  if (smallNumber === Number.NEGATIVE_INFINITY) {
    return 'Process number as -Infinity';
  }
  return smallNumber;
}

console.log(checkNumber(-Number.MAX_VALUE));
// expected output: -1.7976931348623157e+308

console.log(checkNumber(-Number.MAX_VALUE * 2));
// expected output: "Process number as -Infinity"

Number.POSITIVE_INFINITY

Special value representing infinity; returned on overflow.
function checkNumber(bigNumber) {
  if (bigNumber === Number.POSITIVE_INFINITY) {
    return 'Process number as Infinity';
  }
  return bigNumber;
}

console.log(checkNumber(Number.MAX_VALUE));
// expected output: 1.7976931348623157e+308

console.log(checkNumber(Number.MAX_VALUE * 2));
// expected output: Process number as Infinity

Number.prototype

Allows the addition of properties to a Number object.

Methods

Number.isFinite()

The Number.isFinite() method determines whether the passed value is a finite number.
function div(x) {
  if (Number.isFinite(1000 / x)) {
    return 'Number is NOT Infinity.';
  }
  return 'Number is Infinity!';
}

console.log(div(0));
// expected output: "Number is Infinity!"

console.log(div(1));
// expected output: "Number is NOT Infinity."

Number.isInteger()

The Number.isInteger() method determines whether the passed value is an integer.
function fits(x, y) {
  if (Number.isInteger(y / x)) {
    return 'Fits!';
  }
  return 'Does NOT fit!';
}

console.log(fits(5, 10));
// expected output: "Fits!"

console.log(fits(5, 11));
// expected output: "Does NOT fit!"

Number.isNaN()

The Number.isNaN() method determines whether the passed value is NaN and its type is Number. It is a more robust version of the original, global isNaN().
function typeOfNaN(x) {
  if (Number.isNaN(x)) {
    return 'Number NaN';
  }
  if (isNaN(x)) {
    return 'NaN';
  }
}

console.log(typeOfNaN('100F'));
// expected output: "NaN"

console.log(typeOfNaN(NaN));
// expected output: "Number NaN"

Number.isSafeInteger()

The Number.isSafeInteger() method determines whether the provided value is a number that is a safe integer.
function warn(x) {
  if (Number.isSafeInteger(x)) {
    return 'Precision safe.';
  }
  return 'Precision may be lost!';
}

console.log(warn(Math.pow(2, 53)));
// expected output: "Precision may be lost!"

console.log(warn(Math.pow(2, 53) - 1));
// expected output: "Precision safe."

Number.parseFloat()

The Number.parseFloat() method parses a string argument and returns a floating point number. This method behaves identically to the global function parseFloat() and is part of ECMAScript 2015 (its purpose is modularization of globals).
function circumference(r) {
  if (Number.isNaN(Number.parseFloat(r))) {
    return 0;
  }
  return parseFloat(r) * 2.0 * Math.PI ;
}

console.log(circumference('4.567abcdefgh'));
// expected output: 28.695307297889173

console.log(circumference('abcdefgh'));
// expected output: 0

Number.parseInt()

The Number.parseInt() method parses a string argument and returns an integer of the specified radix or base.
function roughScale(x, base) {
  var parsed = Number.parseInt(x, base);
  if (Number.isNaN(parsed)) {
    return 0;
  }
  return parsed * 100;
}

console.log(roughScale(' 0xF', 16));
// expected output: 1500

console.log(roughScale('321', 2));
// expected output: 0

Number.prototype.toExponential()

The Number.parseInt() method parses a string argument and returns an integer of the specified radix or base.
  var parsed = Number.parseInt(x, base);
  if (Number.isNaN(parsed)) {
    return 0;
  }
  return parsed * 100;
}

console.log(roughScale(' 0xF', 16));
// expected output: 1500

console.log(roughScale('321', 2));
// expected output: 0

Number.prototype.toFixed()

The toFixed() method formats a number using fixed-point notation.
function financial(x) {
  return Number.parseFloat(x).toFixed(2);
}

console.log(financial(123.456));
// expected output: "123.46"

console.log(financial(0.004));
// expected output: "0.00"

console.log(financial('1.23e+5'));
// expected output: "123000.00"

Number.prototype.toLocaleString()

The toLocaleString() method returns a string with a language-sensitive representation of this number.
function eArabic(x){
  return x.toLocaleString('ar-EG');
}

console.log(eArabic(123456.789));
// expected output: "١٢٣٬٤٥٦٫٧٨٩"

console.log(eArabic("123456.789"));
// expected output: "123456.789"

console.log(eArabic(NaN));
// expected output: "ليس رقم"

Number.prototype.toPrecision()

The toPrecision() method returns a string representing the Number object to the specified precision.
function precise(x) {
  return Number.parseFloat(x).toPrecision(4);
}

console.log(precise(123.456));
// expected output: "123.5"

console.log(precise(0.004));
// expected output: "0.004000"

console.log(precise('1.23e+5'));
// expected output: "1.230e+5"

Number.prototype.toSource()

The toSource() method returns a string representing the source code of the object.

Number.prototype.toString()

The toString() method returns a string representing the specified Number object.
//  radix
// Optional. An integer in the range 2 through 36 specifying the base to use for representing numeric values. 
numObj.toString([radix])
function hexColour(c) {
  if (c < 256) {
    return Math.abs(c).toString(16);
  }
  return 0;
}

console.log(hexColour(233));
// expected output: "e9"

console.log(hexColour('11'));
// expected output: "b"

Number.prototype.valueOf()

The valueOf() method returns the wrapped primitive value of a Number object.
var numObj = new Number(42);
console.log(typeof numObj);
// expected output: "object"

var num = numObj.valueOf();
console.log(num);
// expected output: 42

console.log(typeof num);
// expected output: "number"


es6中Number.parseInt和Math.trunc使用和功能上有什么区别吗?

在数字极大或是极小时候,会自动采用科学计数法时候,parseInt是会有问题的。
console.log(parseInt(6.022e23)); // 6
console.log(Math.trunc(6.022e23)); // 6.022e+23
  • 功能上可能对于部分结果一致,但是其作用是不一样的。
    parseInt在实际运用上经常会出一些问题,比如0X或是0开头就会出现解析为十六进制或八进制的问题,虽然你可能本意是转换为十进制,但是后端传递值或是用户输入并不会和你想象的一样。
    Math.trunc在ES6更多的是为了补足floor,round,ceil这一系列的方法,以及可想而知,在Math.trunc适用的领域,其性能会比parseInt好不少。
    从另外一个角度上来说,如果给你一个能够完成所有功能的函数,但是需要传递很多不同参数,或是命名功能分类清晰的多种函数,去完成一个项目,你会选择哪种呢?
    个人而言绝对选择是后一种。
  • 简单的说,parseInt() 主要用于将字符串转换成整数,所以哪怕目标本身就是一个数,也极有可能是先转换成字符串再来处理的,这也能解释科学计数法的结果
    Math.trunc 是直接对数值进行处理,理论上来说会快一些也更准确一些。可惜有些浏览器不支持。所以现在用 Math.floor 的比较多,但是要注意处理负数。

二进制和八进制表示法
ES6 提供了二进制和八进制数值的新的写法,分别用前缀0b(或0B)和0o(或0O)表示。
0b111110111 === 503 // true
0o767 === 503 // true
从 ES5 开始,在严格模式之中,八进制就不再允许使用前缀0表示,ES6 进一步明确,要使用前缀0o表示。
// 非严格模式
(function(){
  console.log(0o11 === 011);
})() // true

// 严格模式
(function(){
  'use strict';
  console.log(0o11 === 011);
})() // Uncaught SyntaxError: Octal literals are not allowed in strict mode.
如果要将0b和0o前缀的字符串数值转为十进制,要使用Number方法。
Number('0b111')  // 7
Number('0o10')  // 8

留言