JS Numbers

Numbers are used for mathematical operations and calculations. Learn how JavaScript handles numeric values.

On this page

JS Numbers

JavaScript has only one numeric type: double-precision 64-bit floating point. This means integers and decimals are handled using the same number type.

let x = 10;
let y = 3.14;

console.log(typeof x); // number

Floating Point Precision

Because JavaScript uses binary floating point, some decimal calculations are not exact.

console.log(0.1 + 0.2); // 0.30000000000000004

To control precision, use toFixed() or rounding methods.

let result = 0.1 + 0.2;
console.log(result.toFixed(2)); // 0.30

NaN and Infinity

NaN means "Not a Number". Infinity represents values larger than allowed limits.

console.log(100 / 0);      // Infinity
console.log(-100 / 0);     // -Infinity
console.log("abc" / 2);    // NaN

Parsing Numbers

You can convert strings into numbers using different methods.

console.log(Number("42"));       // 42
console.log(parseInt("42px"));   // 42
console.log(parseFloat("3.14")); // 3.14

Numeric Separators

Modern JavaScript allows underscores to improve readability of large numbers.

let big = 1_000_000;
console.log(big);

JS Number Methods

Number methods format or transform numeric values.

let num = 123.456;

console.log(num.toFixed(2));      // 123.46
console.log(num.toPrecision(4));  // 123.5
console.log(num.toString());      // "123.456"

JS Number Properties

The Number object includes useful static properties.

console.log(Number.MAX_VALUE);
console.log(Number.MIN_VALUE);
console.log(Number.MAX_SAFE_INTEGER);
console.log(Number.MIN_SAFE_INTEGER);
console.log(Number.NaN);

Safe Integers

JavaScript can safely represent integers up to ±(2^53 − 1).

console.log(Number.MAX_SAFE_INTEGER);
console.log(Number.isSafeInteger(9007199254740991));

JS Bitwise

Bitwise operators work on 32-bit integers at the binary level.

console.log(5 & 1);  // AND
console.log(5 | 1);  // OR
console.log(5 ^ 1);  // XOR
console.log(~5);     // NOT
console.log(5 << 1); // left shift
console.log(5 >> 1); // right shift

JS BigInt

BigInt allows working with integers larger than the safe integer limit.

let bigNumber = 123456789012345678901234567890n;
console.log(bigNumber + 10n);

BigInt cannot be mixed directly with regular numbers.

let a = 10n;
// console.log(a + 5); // Error

JS Number Reference

Use the Number reference for a complete list of properties and methods available in JavaScript.

Next Step

Continue with JS Functions to learn how to structure and reuse logic in your programs.

JS Numbers Examples (8)