Advanced20 min read

Numbers & Math

Work with numbers in JavaScript using the Math object, number methods, and understand floating-point precision.

Number Types

In JavaScript, all numbers are floating-point values stored in the IEEE 754 double-precision 64-bit format. There is no separate integer type — 42 and 42.0 are the same thing.

JavaScript has several special numeric values:

javascript
console.log(Infinity);      // Infinity
console.log(-Infinity);     // -Infinity
console.log(1 / 0);         // Infinity
console.log(NaN);           // NaN (Not a Number)
console.log('hello' * 2);   // NaN

NaN is a special value that represents an invalid or undefined mathematical result. Importantly, NaN is not equal to anything, including itself:

javascript
console.log(NaN === NaN); // false

To check for NaN, use Number.isNaN() (preferred) or isNaN():

javascript
Number.isNaN(NaN);       // true
Number.isNaN('hello');   // false (does NOT coerce)
isNaN('hello');           // true (coerces to number first — less reliable)

Converting strings to numbers:

javascript
parseInt('42px');      // 42 (parses until non-digit)
parseFloat('3.14abc'); // 3.14
Number('42');          // 42 (strict — fails on trailing characters)
Number('42px');        // NaN

The Math Object

The Math object provides mathematical constants and functions. It is not a constructor — you use its methods directly.

Rounding methods:

javascript
Math.round(4.5);  // 5 (rounds to nearest integer)
Math.round(4.4);  // 4
Math.floor(4.9);  // 4 (rounds DOWN)
Math.ceil(4.1);   // 5 (rounds UP)
Math.trunc(4.9);  // 4 (removes decimal part)
Math.trunc(-4.9); // -4

Min, max, and absolute value:

javascript
Math.min(1, 5, 3);   // 1
Math.max(1, 5, 3);   // 5
Math.abs(-42);        // 42

Powers and roots:

javascript
Math.pow(2, 8);  // 256 (2 to the power of 8)
2 ** 8;          // 256 (exponentiation operator — same result)
Math.sqrt(144);  // 12

Random numbers:

Math.random() returns a floating-point number in the range [0, 1) — from 0 (inclusive) up to but not including 1.

javascript
Math.random();                          // e.g. 0.7362...
Math.floor(Math.random() * 10);         // random integer 0–9
Math.floor(Math.random() * 10) + 1;     // random integer 1–10
Math.floor(Math.random() * (max - min + 1)) + min; // random in range

Number Methods

Numbers in JavaScript have several useful methods.

toFixed(digits) formats a number with a fixed number of decimal places. It returns a string:

javascript
const pi = 3.14159;
console.log(pi.toFixed(2));  // '3.14'
console.log(pi.toFixed(0));  // '3'
console.log(pi.toFixed(4));  // '3.1416' (rounds)

toPrecision(digits) formats a number to a specified total number of significant digits:

javascript
const num = 123.456;
console.log(num.toPrecision(5)); // '123.46'
console.log(num.toPrecision(2)); // '1.2e+2'

toString(radix) converts a number to a string in the given base:

javascript
const num = 255;
console.log(num.toString(16)); // 'ff' (hexadecimal)
console.log(num.toString(2));  // '11111111' (binary)

Static methods on Number:

javascript
Number.isInteger(42);     // true
Number.isInteger(42.5);   // false
Number.isFinite(42);      // true
Number.isFinite(Infinity); // false
Number.isFinite(NaN);     // false

Floating-Point Gotchas

One of the most surprising things in JavaScript (and most programming languages) is this:

javascript
console.log(0.1 + 0.2);          // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3);  // false!

Why does this happen? Numbers are stored in binary (base 2). Just as 1/3 cannot be exactly represented in decimal (0.333...), values like 0.1 and 0.2 cannot be exactly represented in binary. The tiny rounding errors accumulate.

Workarounds:

  1. Multiply, operate, then divide — work with integers:
javascript
const result = (0.1 * 10 + 0.2 * 10) / 10; // 0.3
  1. Use toFixed() for display:
javascript
const sum = 0.1 + 0.2;
console.log(sum.toFixed(2)); // '0.30'
console.log(Number(sum.toFixed(2))); // 0.3
  1. Use an epsilon for comparisons:
javascript
const EPSILON = Number.EPSILON;
console.log(Math.abs(0.1 + 0.2 - 0.3) < EPSILON); // true

This is not a JavaScript bug — it is a fundamental property of IEEE 754 floating-point arithmetic used by virtually all modern programming languages.

Math Methods in Action

html
<div id="output"></div>

<script>
  // Rounding
  const pi = Math.PI;
  const rounded = Math.round(pi);   // 3
  const floored = Math.floor(pi);   // 3
  const ceiled = Math.ceil(pi);     // 4
  const fixed = pi.toFixed(2);      // '3.14'

  // Random integer between 1 and 100
  const random = Math.floor(Math.random() * 100) + 1;

  // Powers
  const squared = Math.pow(7, 2);   // 49
  const cubeRoot = Math.cbrt(27);   // 3

  const output = document.getElementById('output');
  output.innerHTML = `
    <p>Math.PI: ${pi}</p>
    <p>Rounded: ${rounded} | Floor: ${floored} | Ceil: ${ceiled}</p>
    <p>Fixed (2 decimals): ${fixed}</p>
    <p>Random (1-100): ${random}</p>
    <p>7 squared: ${squared} | Cube root of 27: ${cubeRoot}</p>
  `;
</script>

What does Math.floor(4.9) return?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.