Skip to content

Number representations

The number is a primitive type representing both integer and floating point values, such as

const iAmANumber = 7;
const anotherNumber = 17.12423412312;

console.log(typeof(iAmANumber)); // number
console.log(typeof(anotherNumber)); // number
console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991 so 2^53 - 1.

NaN - not a number

There is a special value of number in JavaScript. This is the NaN value, which is Not a Number. This value represents something that is not a number. Most often, we can meet it when performing numerical operations, when one of the values is of an inappropriate type (e.g. is a string instead of a number). To check if a value is equal to Nan, we can use the isNan() function, e.g:

console.log(typeof(Number.NaN)); // number
Number.isNaN(3 / 'notANumberReally'); // true

The number primitive, which is wrapped by object Number has a number of useful methods. Some of them are:

  • parseInt - creates an integer from the input string
  • parseFloat - creates a floating point number from the input thong
  • toFixed - allows you to format a numeric value to a specific decimal place given as an argument. Rounds up if necessary.
  • toString - converts a numeric value to string.

The following example shows the use of these methods:

Number.parseInt('4'); // 4
Number.parseInt('five'); // NaN

Number.parseFloat('17.12'); // 17.12

123.45678.toFixed(4); // 123.4568 - rounded up

Number(8).toString(); // "8"

BigInt

bigint is another primitive in JS representing numerical values. Unlike the number, it only stores integers and its maximum value is greater than the maximum value of the number. To mark a numeric value as bigint, we should add the letter n at its end, e.g:

const iAmBigInt = 9007199254740992n;
console.log(typeof(iAmBigInt)); //bigint

const sumOfBigInts = 2n + 3n;
console.log(sumOfBigInts); // 5n

NOTE: The Math object, contains a set of methods for mathematical operations. These methods work only for number.

NOTE: When performing mathematical operations we should not mix the number and bigint types.