JavaScript Tutorial · JavaScript Basics · Lesson 7 of 44
JavaScript Numbers
Integers, decimals, NaN, rounding and converting text to numbers.
One number type
JavaScript has a single number type for both integers and decimals (64-bit floating point).
const a = 7;
const b = 2;
console.log(a + b, a - b, a * b, a / b);
console.log(a % b); // remainder
console.log(a ** b); // power
Output
9 5 14 3.5 1 49
Floating-point surprises
Like most languages, JavaScript stores decimals in binary, so some results are slightly off. When working with money, store cents as integers or round for display with toFixed():
console.log(0.1 + 0.2);
console.log((0.1 + 0.2).toFixed(2));
const priceCents = 1999 + 501;
console.log(`$${(priceCents / 100).toFixed(2)}`);
Output
0.30000000000000004 0.30 $25.00
NaN and Infinity
NaN ("Not a Number") is the result of an invalid calculation. It is the only value not equal to itself, so test it with Number.isNaN().
const result = "abc" * 3;
console.log(result);
console.log(result === NaN);
console.log(Number.isNaN(result));
console.log(1 / 0);
Output
NaN false true Infinity
Useful number methods
console.log(Number("42"));
console.log(Number.parseInt("42px"));
console.log(Number.parseFloat("3.75 kg"));
console.log(Math.round(4.5), Math.floor(4.9), Math.ceil(4.1));
console.log(Number.isInteger(10), Number.isInteger(10.5));
console.log((1234567.891).toLocaleString("en-US"));
Output
42 42 3.75 5 4 5 true false 1,234,567.891
For integers larger than Number.MAX_SAFE_INTEGER (2⁵³ − 1), use BigInt by adding n: 2n ** 64n.
Test yourself
How do you reliably check whether a value is NaN?
value === NaNvalue == NaNNumber.isNaN(value)typeof value === 'NaN'
Show answer
Answer: Number.isNaN(value)