JavaScript - - By Aurelio De Rosa

Preparing for ECMAScript 6: New Number Methods

In this series about the new features of ECMAScript 6, we’ve discussed new methods available for the String and Array data types, but also new types of data like Map and WeakMap.

In this article I’m going to introduce you to the new methods and constants added to the Number data type. Some of the methods covered, as we’ll see, aren’t new at all but they have been improved and/or moved under the right object (for example isNaN()). As always, we’ll also put the new knowledge acquired into action with some examples. So, without further ado, let’s start.

Number.isInteger()

The first method I want to cover is Number.isInteger(). It’s a new addition to JavaScript and this is something you may have defined and used by yourself in the past. It determines whether the value passed to the function is an integer or not. This method returns true if the passed value is an integer, and false otherwise. The implementation of this method was pretty easy but it’s still good to have it natively. One of the possible solutions to recreate this function is:

Number.isInteger = Number.isInteger || function (number) {
   return typeof number === 'number' && number % 1 === 0;
};

For my fun, I tried to recreate this function and I ended up with a different approach:

Number.isInteger = Number.isInteger || function (number) {
   return typeof number === 'number' && Math.floor(number) === number;
};

Both these functions are good and useful but they don’t respect the ECMAScript 6 specifications. So, if you want to polyfill this method you need something a little bit more complex as we’ll see in a few moments. For the moment, let’s start by discovering the syntax of Number.isInteger():

Number.isInteger(number)

The number argument represents the value you want to test.

Some examples of use of this method are shown below:

// prints "true"
console.log(Number.isInteger(19));

// prints "false"
console.log(Number.isInteger(3.5));

// prints "false"
console.log(Number.isInteger([1, 2, 3]));

A live demo of the previous code is shown below and also available as a JSFiddle.

The method is supported by almost any modern browser and specifically by Firefox, Chrome, Opera, and Safari. If you want to support Internet Explorer and some other browsers, you need a polyfill. One that you can employ is available on the Mozilla Developer Network on the method’s page and also reported below for your convenience:

if (!Number.isInteger) {
  Number.isInteger = function isInteger (nVal) {
    return typeof nVal === "number" &&
           isFinite(nVal) && nVal > -9007199254740992 &&
           nVal < 9007199254740992 &&
           Math.floor(nVal) === nVal;
  };
}

Number.isNaN()

If you’ve written any JavaScript code in the past, this method should not be new to you. For a while now, JavaScript has had a method called isNaN() that is exposed through the window object. This method tests if a value is equal to NaN, in which case it returns true, or not, in which case false is returned. The problem with window.isNaN() is that it has an issue in that it returns true also for values that converted to a number will be NaN. To give you a concrete idea of this issue, all the following statements return true:

// prints "true"
console.log(window.isNaN(0/0));

// prints "true"
console.log(window.isNaN('test'));

// prints "true"
console.log(window.isNaN(undefined));

// prints "true"
console.log(window.isNaN({prop: 'value'}));

What you might need is a method that returns true only if the NaN value is passed. That’s why ECMAScript 6 has introduced the Number.isNaN() method. Its syntax is pretty much what you’d expect:

Number.isNaN(value)

Where value is the value you want to test. Some example uses of this method are shown below:

// prints "true"
console.log(Number.isNaN(0/0));

// prints "true"
console.log(Number.isNaN(NaN));

// prints "false"
console.log(Number.isNaN(undefined));

// prints "false"
console.log(Number.isNaN({prop: 'value'}));

As you can see, testing the same values we obtain different results.

A live demo of the previous snippet is shown below and also available as a JSFiddle.

The method is currently only supported by Firefox, Chrome and Opera. If you want to support other browsers, a very simple polyfill for this method is the following:

Number.isNaN = Number.isNaN || function (value) {
   return value !== value;
};

The reason why it works is because NaN is the only non-reflexive value in JavaScript, which means that it is the only value that isn’t equal to itself.

Number.isFinite()

This method shares the same story as the previous one. In JavaScript there is a method called window.isFinite() that tests if a value passed is a finite number or not. Unfortunately, it also returns true for values that converted to a number will be a finite number. Examples of this issue are reported below:

// prints "true"
console.log(window.isFinite(10));

// prints "true"
console.log(window.isFinite(Number.MAX_VALUE));

// prints "true"
console.log(window.isFinite(null));

// prints "true"
console.log(window.isFinite([]));

For this reason, in ECMAScript 6 there is a method called isFinite() that belongs to Number. Its syntax is the following:

Number.isFinite(value)

Where value is the value you want to test. If you test the same values from the previous snippet, you can see that the results are different:

// prints "true"
console.log(Number.isFinite(10));

// prints "true"
console.log(Number.isFinite(Number.MAX_VALUE));

// prints "false"
console.log(Number.isFinite(null));

// prints "false"
console.log(Number.isFinite([]));

A live demo of the previous snippet is shown below and also available as a JSFiddle.

The method is currently only supported by Firefox, Chrome and Opera. You can find a polyfill for it on the method’s page on MDN.

Number.isSafeInteger()

The Number.isSafeInteger() method is a completely new addition to the next version of JavaScript. It tests whether the value passed is a number that is a safe integer in which case it returns true. A safe integer is defined as an integer that satisfies both the following two conditions:

  • The number can be exactly represented as an IEEE-754 double precision number
  • The IEEE-754 representation of the number can’t be the result of rounding any other integer to fit the IEEE-754 representation

Based on this definition, the safe integers are all the integers from -(253 – 1) inclusive to 253 – 1 inclusive. These values are important and we’ll discuss them a bit more at the end of this section.

The syntax of this method is:

Number.isSafeInteger(value)

Where value is the value you want to test. A few example uses of this method are shown below:

// prints "true"
console.log(Number.isSafeInteger(5));

// prints "false"
console.log(Number.isSafeInteger('19'));

// prints "false"
console.log(Number.isSafeInteger(Math.pow(2, 53)));

// prints "true"
console.log(Number.isSafeInteger(Math.pow(2, 53) - 1));

A live demo of this code is shown below and also available as a JSFiddle.

The Number.isSafeInteger() method is supported by Firefox, Chrome and Opera. A polyfill for this method, extracted from es6-shim by Paul Miller, is:

Number.isSafeInteger = Number.isSafeInteger || function (value) {
   return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;
};

Note that this polyfill relies on the Number.isInteger() method discussed before, so you need to polyfill the latter as well to use this one.

ECMAScript 6 “Harmony” also introduces two related constant values: Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER. The former represents the maximum safe integer in JavaScript, that is 253 – 1, while the latter the minimum safe integer which is -(253 – 1). As you might note, these are the same values I cited earlier.

Number.parseInt() and Number.parseFloat()

The Number.parseInt() and Number.parseFloat() methods are covered in the same section because, unlike other similar methods mentioned in this article, they already existed in previous version of ECMAScript but aren’t different from their old global version. So, you can use them in the same way you’ve done so far and you can expect the same results. They have been added to Number because they actually belonged to it from the very beginning.

For the sake of completeness I’m reporting their syntax:

// Signature of Number.parseInt
Number.parseInt(string, radix)

// Signature of Number.parseFloat
Number.parseFloat(string)

Where string represents the value you want to parse and radix is the radix you want to use to convert string.

The following snippet shows a few example uses:

// Prints "-3"
console.log(Number.parseInt('-3'));

// Prints "4"
console.log(Number.parseInt('100', 2));

// Prints "NaN"
console.log(Number.parseInt('test'));

// Prints "NaN"
console.log(Number.parseInt({}));

// Prints "42.1"
console.log(Number.parseFloat('42.1'));

// Prints "NaN"
console.log(Number.parseFloat('test'));

// Prints "NaN"
console.log(Number.parseFloat({}));

A live demo of this code is displayed below and also available as a JSFiddle.

These methods are currently implemented in Firefox, Chrome, and Opera. In case you want to polyfill them, you can simply call their related global method as listed below:

// Polyfill Number.parseInt
Number.parseInt = Number.parseInt || function () {
   return window.parseInt.apply(window, arguments); 
};

// Polyfill Number.parseFloat
Number.parseFloat = Number.parseFloat || function () {
   return window.parseFloat.apply(window, arguments); 
};

Conclusion

In this tutorial we’ve covered the new methods and constants added in ECMAScript 6 that work with the Number data type. It’s worth noting that the new version of JavaScript also has added another constant that I didn’t mention so far. This constant is Number.EPSILON and represents the difference between one and the smallest value greater than one that can be represented as a Number. With this last note, we’ve concluded our journey for the Number data type.

Sponsors