[JavaScript – ES2015] Number and Math

ES2015 enriches the existing built-in objects with more functionalities. This post focuses on Number and Math objects.


1. Number

All number types in JavaScript is actually the type of “Number“.

let int = 10;
let float = 2.5;
let hex = 0xa;
console.log('int: ' + (typeof int));
console.log('double: ' + (typeof float));
console.log('hex: ' + (typeof hex));

They are all “number” type.


2. Parsing Numbers

You have been used “parseInt()” or “parseFloat()” functions to convert strings to numbers. The problem is that they are global functions. The solution in ES2015 is that they are moved into the “Number” class and the global ones are depreciated.

console.log(Number.parseInt("10")); // 10
console.log(Number.parseInt("9.1")); // 9
console.log(Number.parseInt("10.9")); // 10

console.log(Number.parseInt("10", 10)); // 10
console.log(Number.parseInt("10", 8)); // 8
console.log(Number.parseInt("10", 16)); // 16
console.log(Number.parseInt("0x10", 10)); // 0
console.log(Number.parseInt("0x10", 16)); // 16

console.log(Number.parseFloat("2.4")); // 2.4

It is always a good idea to specify the base when you use the “parseInt()” method.


3. Checking Numbers

Another improvement is that the “Number” object has the methods that check the number is number, finite, or integer.

  • Number.isNaN()
  • Number.isFinite()
  • Number.isInteger()
  • Number.isSafeInteger() : can be exactly represented as an IEEE-754 double precision number
let intVal = 1;
let floatVal = 1.1;

console.log(Number.isNaN(Number.NaN)); // true
console.log(Number.isNaN(intVal)); // false
console.log(Number.isNaN(Number("bogus"))); // true

console.log(Number.isFinite(Number.POSITIVE_INFINITY)); // false
console.log(Number.isFinite(intVal)); // true

console.log(Number.isInteger(floatVal)); // false
console.log(Number.isInteger(intVal)); // true

JavaScript can represent a really big numbers but you might want to limit the value in a safe scope: Number.MIN_SAFE_INTEGER -(2^53 -1) ~ Number.MAX_SAFE_INTEGER (2^53 -1). To check the number is within this scope, use the “Number.isSafeInteger()” method.


4. Math

The “Math” object has been provided the wide range of mathematical functions. ES2015 even expands this.

Please refer to the following document for the full reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s