How to Use the Number Object

This article describes Number, a primitive wrapper object used to represent and manipulate numbers. "Number" represents floating point numbers like 45 or -3.24. Numbers are encoded as 64-bit binary, much like double in Java. There are some helpful functions in "Number" like Number ("123") would return the actual number 123. However, a "Number" ("Iamnotanumber") would return NaN (Not-a-Number) because it could not convert that into a number.

Examples

Using the Number object to assign values to numeric variables

The following example uses the Number object's properties to assign values to several numeric variables:

const biggestNum = Number.MAX_VALUE;
const smallestNum = Number.MIN_VALUE;
const infiniteNum = Number.POSITIVE_INFINITY;
const negInfiniteNum = Number.NEGATIVE_INFINITY;
const notANum = Number.NaN;


Integer range for Number

The following example shows the minimum and maximum integer values that can be represented as Number object.

const biggestInt = Number.MAX_SAFE_INTEGER; // (2**53 - 1) => 9007199254740991
const smallestInt = Number.MIN_SAFE_INTEGER; // -(2**53 - 1) => -9007199254740991

When parsing data that has been serialized to JSON, integer values falling outside of this range can be expected to become corrupted when JSON parser coerces them to Number type.

A possible workaround is to use String instead.

Larger numbers can be represented using the BigInt type.


Using Number() to convert a Date object

The following example converts the Date object to a numerical value using Number as a function:

const d = new Date("1995-12-17T03:24:00");
console.log(Number(d));

This logs 819199440000.


Convert numeric strings and null to numbers

Number("123"); // 123
Number("123") === 123; // true
Number("12.3"); // 12.3
Number("12.00"); // 12
Number("123e-1"); // 12.3
Number(""); // 0
Number(null); // 0
Number("0x11"); // 17
Number("0b11"); // 3
Number("0o11"); // 9
Number("foo"); // NaN
Number("100a"); // NaN
Number("-Infinity"); // -Infinity