Numbers and math

Topic 3 of 5 in Variables & types7 min readBeginnerFree course

Overview

JavaScript has one main number type for both whole numbers and decimals. Under the hood every number is a 64-bit “double-precision floating point” value — the same format most languages use for decimals.

JavaScript
const items = 3;
const price = 4.99;
console.log(items * price); // 14.97

Numbers can be written in several ways:

JavaScript
1000000;     // ordinary
1_000_000;   // underscores for readability — same value
2.5e6;       // scientific notation: 2,500,000
0.000_001;   // also fine
0xff;        // hexadecimal: 255
0b1010;      // binary: 10

Arithmetic operators

JavaScript
10 + 3;  // 13
10 - 3;  // 7
10 * 3;  // 30
10 / 3;  // 3.3333333333333335
10 % 3;  // 1   (remainder)
2 ** 3;  // 8   (exponent)

The usual maths order applies: ** first, then *, / and %, then + and -. Use parentheses to make your intent obvious:

JavaScript
2 + 3 * 4;    // 14
(2 + 3) * 4;  // 20

The remainder operator

% gives what’s left over after division. It’s surprisingly useful:

JavaScript
7 % 2 === 1;      // odd number check
10 % 5 === 0;     // divisible by 5
(index + 1) % 3;  // cycle 1, 2, 0, 1, 2, 0 …

Updating a number

JavaScript
let count = 10;
count += 5;  // 15  (same as count = count + 5)
count -= 2;  // 13
count *= 2;  // 26
count /= 2;  // 13
count++;     // 14  (add one)
count--;     // 13  (subtract one)

The Math object

Math is a built-in object full of maths helpers and constants.

JavaScript
Math.round(4.6);           // 5
Math.floor(4.6);           // 4
Math.ceil(4.1);            // 5
Math.trunc(-4.6);          // -4
Math.max(3, 9, 2);         // 9
Math.min(3, 9, 2);         // 2
Math.abs(-7);              // 7
Math.sqrt(16);             // 4
Math.PI;                   // 3.141592653589793
Math.random();             // a number from 0 up to (not including) 1

Four ways to round

The four rounding functions only disagree when numbers have a fractional part — and especially when they’re negative:

On a number line, 4.6 rounds down to 4 with floor and trunc, and up to 5 with ceil and round. −4.6 rounds to −5 with floor and round, and to −4 with ceil and trunc.

  • Math.floor always moves down (towards −∞).
  • Math.ceil always moves up (towards +∞).
  • Math.trunc simply chops off the decimal part (towards 0).
  • Math.round goes to the nearest whole number; exactly .5 goes up.

Random numbers

Math.random() returns a decimal from 0 up to (but not including) 1. Scale and floor it to get whole numbers in a range. A random whole number from 1 to 6:

JavaScript
const roll = Math.floor(Math.random() * 6) + 1;

Step by step: Math.random() * 6 gives 0 to 5.999…; Math.floor turns that into 0–5; + 1 shifts it to 1–6. Picking a random item from an array uses the same idea:

JavaScript
const colours = ['red', 'green', 'blue'];
const pick = colours[Math.floor(Math.random() * colours.length)];

Not for passwords or tokens. Math.random() is predictable enough for games but not for security. Use crypto.getRandomValues() or crypto.randomUUID() instead.

Decimal surprises

Numbers are stored in binary, so some decimals — like 0.1 — can’t be represented exactly, in the same way 1/3 can’t be written exactly in decimal (0.333…). Tiny errors appear:

JavaScript
0.1 + 0.2;              // 0.30000000000000004
0.1 + 0.2 === 0.3;      // false
(0.1 + 0.2).toFixed(2); // '0.30'

To compare decimals, check that they’re close enough rather than exactly equal:

JavaScript
Math.abs((0.1 + 0.2) - 0.3) < Number.EPSILON; // true

Working with money? Store amounts in the smallest unit (cents or paise) as whole numbers, and divide only when you display them. 1999 cents is always exact; 19.99 might not be.

Formatting numbers

JavaScript
(4.5).toFixed(2);        // '4.50'  — fixed decimal places (returns a string)
(1234.5678).toFixed(1);  // '1234.6'
(0.000123).toPrecision(2); // '0.00012'

(1234567.891).toLocaleString('en-IN'); // '12,34,567.891'
(1234567.891).toLocaleString('en-US'); // '1,234,567.891'

For currencies, Intl.NumberFormat handles symbols and separators for any locale:

JavaScript
const rupees = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' });
rupees.format(1499.5); // '₹1,499.50'

Converting text to numbers

Values from forms and URLs arrive as strings. Convert them before doing maths:

JavaScript
Number('42');        // 42
Number('42px');      // NaN — the whole string must be a number
Number('');          // 0   — careful!
parseInt('42px');    // 42  — reads digits until it hits something else
parseFloat('3.5kg'); // 3.5
+'7';                // 7   — unary plus, a common shorthand

parseInt should be given a base (radix) when the input could be ambiguous: parseInt('08', 10).

Special values

NaN (“not a number”) appears when maths fails, such as Number('abc') or 0 / 0. Any maths involving NaN also gives NaN, and NaN is the only value that isn’t equal to itself — so check for it with Number.isNaN(value).

JavaScript
Number.isNaN(Number('abc')); // true
NaN === NaN;                 // false!
Number.isInteger(5.0);       // true
Number.isInteger(5.5);       // false
1 / 0;                       // Infinity
-1 / 0;                      // -Infinity
Number.isFinite(1 / 0);      // false

Safe integers

Whole numbers are exact up to Number.MAX_SAFE_INTEGER (about 9 quadrillion). Beyond that, numbers start skipping values. Use BigInt (123n) when you need exact arithmetic on bigger whole numbers.

Exercise

Round a price

Write formatPrice(n) that returns the number rounded to 2 decimal places as a string, e.g. formatPrice(4.5) → '4.50'. Then write randomBetween(min, max) that returns a random whole number from min to max, inclusive.

JavaScript
function formatPrice(n) {
  // your code here
}

function randomBetween(min, max) {
  // your code here
}

Summary

  • All JavaScript numbers are 64-bit floating point; use BigInt for huge whole numbers.
  • % gives the remainder and ** raises to a power; ++/-- add or subtract one.
  • Math holds helpers like Math.round, Math.floor, Math.max and Math.random.
  • Decimals can be slightly off — round when you display them, and store money in whole cents.
  • Convert text with Number() and check for failure with Number.isNaN().