This article covers new and improved number methods in ES6 (ECMAScript 6).
It’s part of a series about the new features of ES6, in which we’ve also discussed new methods available for the String and Array data types, but also new types of data like Map and WeakMap.
I’ll introduce you to the new methods and constants added to the Number data type. Some of the number methods covered, as we’ll see, aren’t new at all, but they’ve 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 get started.
Key Takeaways
- ES6 introduced several new number methods, including Number.isInteger(), Number.isNaN(), Number.isFinite(), Number.isSafeInteger(), Number.parseInt(), and Number.parseFloat().
- Number.isInteger() checks whether the passed value is an integer, Number.isNaN() tests if a value is equal to NaN, and Number.isFinite() tests if a value passed is a finite number.
- Number.isSafeInteger() tests whether the value passed is a number that is a safe integer, defined as an integer that can be exactly represented as an IEEE-754 double precision number.
- Number.parseInt() and Number.parseFloat() are not new, but they have been moved under the Number object for the purpose of modularization of globals. They parse a string argument and return an integer and a floating point number respectively.
- ES6 also introduced two related constant values: Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER which represent the maximum and minimum safe integer in JavaScript.
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:
<span>Number.isInteger = Number.isInteger || function (number) { </span> <span>return typeof number === 'number' && number % 1 === 0; </span><span>}; </span>
Just for fun, I tried to recreate this function and I ended up with a different approach:
<span>Number.isInteger = Number.isInteger || function (number) { </span> <span>return typeof number === 'number' && Math.floor(number) === number; </span><span>}; </span>
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 shortly. For the moment, let’s start by discovering the syntax of Number.isInteger():
<span>Number.isInteger(number) </span>
The number argument represents the value you want to test.
Some examples of the use of this method are shown below:
<span>// prints 'true' </span><span>console.log(Number.isInteger(19)); </span> <span>// prints 'false' </span><span>console.log(Number.isInteger(3.5)); </span> <span>// prints 'false' </span><span>console.log(Number.isInteger([1, 2, 3])); </span>
A live demo of the previous code is shown below and is also available at JSBin.
The method is supported in Node and all modern browsers, with the exception of Internet Explorer. If you need to support older browsers, you can employ a polyfill, such as the one available on the Mozilla Developer Network on the methods page. This is also reproduced below for your convenience:
<span>Number.isInteger = Number.isInteger || function (number) { </span> <span>return typeof number === 'number' && number % 1 === 0; </span><span>}; </span>
Number.isNaN()
If you’ve written any JavaScript code in the past, this method shouldn’t be new to you. For a while now, JavaScript has had a method called isNaN() that’s exposed through the window object. This method tests if a value is equal to NaN, in which case it returns true, or otherwise false. The problem with window.isNaN() is that it has an issue in that it also returns true 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:
<span>Number.isInteger = Number.isInteger || function (number) { </span> <span>return typeof number === 'number' && Math.floor(number) === number; </span><span>}; </span>
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:
<span>Number.isInteger(number) </span>
Here, value is the value you want to test. Some example uses of this method are shown below:
<span>// prints 'true' </span><span>console.log(Number.isInteger(19)); </span> <span>// prints 'false' </span><span>console.log(Number.isInteger(3.5)); </span> <span>// prints 'false' </span><span>console.log(Number.isInteger([1, 2, 3])); </span>
As you can see, testing the same values we obtain different results.
A live demo of the previous snippet is shown below and is also available at JSBin.
The method is supported in Node and all modern browsers, with the exception of Internet Explorer. If you want to support other browsers, a very simple polyfill for this method is the following:
<span>if (!Number.isInteger) { </span> <span>Number.isInteger = function isInteger (nVal) { </span> <span>return typeof nVal === 'number' && </span> <span>isFinite(nVal) && </span> nVal <span>> -9007199254740992 && </span> nVal <span> <span>Math.floor(nVal) === nVal; </span> <span>}; </span><span>} </span></span>
The reason this works is because NaN is the only non-reflexive value in JavaScript, which means that it’s the only value that isn’t equal to itself.
Number.isFinite()
This method shares the same story as the previous one. In JavaScript there’s 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 demonstrated below:
<span>// prints 'true' </span><span>console.log(window.isNaN(0/0)); </span> <span>// prints 'true' </span><span>console.log(window.isNaN('test')); </span> <span>// prints 'true' </span><span>console.log(window.isNaN(undefined)); </span> <span>// prints 'true' </span><span>console.log(window.isNaN({prop: 'value'})); </span>
For this reason, in ECMAScript 6 there’s a method called isFinite() that belongs to Number. Its syntax is the following:
<span>Number.isNaN(value) </span>
Here, 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:
<span>// prints 'true' </span><span>console.log(Number.isNaN(0/0)); </span> <span>// prints 'true' </span><span>console.log(Number.isNaN(NaN)); </span> <span>// prints 'false' </span><span>console.log(Number.isNaN(undefined)); </span> <span>// prints 'false' </span><span>console.log(Number.isNaN({prop: 'value'})); </span>
A live demo of the previous snippet is shown below and is also available at JSBin.
The method is supported in Node and all modern browsers, with the exception of Internet Explorer. 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 ES6. 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, safe integers are all the integers from -(253 – 1) inclusive to 253 – 1 inclusive. These values are important and we’ll discuss them a little more at the end of this section.
The syntax of this method is:
<span>Number.isInteger = Number.isInteger || function (number) { </span> <span>return typeof number === 'number' && number % 1 === 0; </span><span>}; </span>
Here, value is the value you want to test. A few example uses of this method are shown below:
<span>Number.isInteger = Number.isInteger || function (number) { </span> <span>return typeof number === 'number' && Math.floor(number) === number; </span><span>}; </span>
A live demo of this code is shown below and also available at JSBin.
The Number.isSafeInteger() is supported in Node and all modern browsers, with the exception of Internet Explorer. A polyfill for this method, extracted from es6-shim by Paul Miller, is:
<span>Number.isInteger(number) </span>
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 also introduced 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 a 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. The purpose of adding these methods to Number is the modularization of globals.
For the sake of completeness, I’m reporting their syntax:
<span>// prints 'true' </span><span>console.log(Number.isInteger(19)); </span> <span>// prints 'false' </span><span>console.log(Number.isInteger(3.5)); </span> <span>// prints 'false' </span><span>console.log(Number.isInteger([1, 2, 3])); </span>
Here, 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:
<span>if (!Number.isInteger) { </span> <span>Number.isInteger = function isInteger (nVal) { </span> <span>return typeof nVal === 'number' && </span> <span>isFinite(nVal) && </span> nVal <span>> -9007199254740992 && </span> nVal <span> <span>Math.floor(nVal) === nVal; </span> <span>}; </span><span>} </span></span>
A live demo of this code is displayed below and is also available at JSBin.
These methods are supported in Node and all modern browsers, with the exception of Internet Explorer. In case you want to polyfill them, you can simply call their related global method as listed below:
<span>Number.isInteger = Number.isInteger || function (number) { </span> <span>return typeof number === 'number' && number % 1 === 0; </span><span>}; </span>
Browser Support
The following graphic depicts browser support for extensions to the built-in Number object in ES6. Mouse over the boxes to see the percentage use of the respective browser versions.
Can I Use es6-number? Data on support for the es6-number feature across the major browsers from caniuse.com.
ES6 Number Methods: Wrapping Up
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 ES6 has also has added another constant that I haven’t mentioned so far. This 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.
Frequently Asked Questions (FAQs) about ES6 Number Methods
What are the new ES6 number methods and how do they work?
ES6 introduced several new number methods that make it easier to work with numbers in JavaScript. These include Number.isFinite(), Number.isInteger(), Number.isNaN(), Number.parseFloat(), and Number.parseInt(). Each of these methods performs a specific function. For example, Number.isFinite() checks if a value is a finite number, while Number.isInteger() checks if a value is an integer. Number.isNaN() checks if a value is NaN (Not a Number), and Number.parseFloat() and Number.parseInt() parse a string argument and return a floating point number and an integer respectively.
How does the Number.EPSILON method work in ES6?
Number.EPSILON in ES6 is a new constant that represents the smallest interval between two representable numbers. It’s particularly useful when comparing floating point numbers for equality. Due to the way floating point numbers are represented in computers, they may not be exactly equal even if they appear to be. Number.EPSILON can be used to check if the difference between two numbers is less than this smallest interval, indicating that they are effectively equal.
What is the purpose of the Number.isSafeInteger() method in ES6?
The Number.isSafeInteger() method in ES6 is used to determine if a value is a safe integer. A safe integer is a number that can be exactly represented as an IEEE-754 double precision number, which means it’s within the range of -(2^53 – 1) and 2^53 – 1. This method is useful when you want to ensure that a number can be accurately represented in JavaScript, which can be important in certain mathematical operations.
How does the Number.parseInt() method differ from the global parseInt() function?
The Number.parseInt() method in ES6 is essentially the same as the global parseInt() function, but it’s part of the Number object. This means you can call it as a method on the Number object, rather than as a standalone function. The functionality is the same – it converts a string to an integer at a specified radix or base.
What is the significance of the Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER constants in ES6?
The Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER constants in ES6 represent the maximum and minimum safe integer values in JavaScript. A safe integer is one that can be exactly represented as an IEEE-754 double precision number. These constants are useful when you need to check if a number is within the safe integer range, which can be important in certain mathematical operations.
How can I use the Number.isNaN() method in ES6?
The Number.isNaN() method in ES6 is used to determine if a value is NaN (Not a Number). This is different from the global isNaN() function, which converts its argument to a number before testing it. Number.isNaN() does not perform this conversion, so it only returns true if the argument is the actual NaN value, and not if the argument is a value that can’t be converted to a number.
What is the use of Number.isFinite() method in ES6?
The Number.isFinite() method in ES6 is used to determine if a value is a finite number. This is different from the global isFinite() function, which converts its argument to a number before testing it. Number.isFinite() does not perform this conversion, so it only returns true if the argument is a finite number, and not if the argument is a value that can’t be converted to a number.
How does the Number.parseFloat() method work in ES6?
The Number.parseFloat() method in ES6 is essentially the same as the global parseFloat() function, but it’s part of the Number object. This means you can call it as a method on the Number object, rather than as a standalone function. The functionality is the same – it parses a string argument and returns a floating point number.
How can I use the Number.isInteger() method in ES6?
The Number.isInteger() method in ES6 is used to determine if a value is an integer. This method returns true if the value is a number that is not Infinity, not NaN, and can be expressed without a fractional component. It’s useful when you need to check if a number is an integer, which can be important in certain mathematical operations.
What are the practical applications of the new ES6 number methods?
The new ES6 number methods provide more robust and precise ways to work with numbers in JavaScript. They can be used to check if a number is finite, an integer, NaN, or a safe integer, and to parse strings into numbers. These methods can be particularly useful in mathematical operations, data validation, and anywhere else where precise control over numbers is required.
The above is the detailed content of Preparing for ECMAScript 6: New Number Methods. For more information, please follow other related articles on the PHP Chinese website!

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools
