Skip to content

Numbers and Math

Learn how numbers work in code: integers, floats, arithmetic operators, rounding, and the Math object.

What you'll learn

  • How numbers are represented in JavaScript (integers and floats)
  • Arithmetic operators and operator precedence
  • The Math object: rounding, powers, random, min/max
  • Common pitfalls with floating-point precision
  • How to convert strings to numbers safely

Concept

Numbers and Math

Numbers are the other fundamental data type alongside strings. JavaScript has a single numeric type called Number that represents both integers (42) and decimals (3.14). Understanding how numbers behave — especially their limitations — prevents a whole class of subtle bugs.

Arithmetic Operators

The basic operators are + (add), - (subtract), * (multiply), / (divide), and % (modulo — the remainder). There are also compound assignment operators like +=, -=, *=, and /= that combine an operation with assignment:

let total = 10;
total += 5;   // total is now 15 (same as total = total + 5)
total *= 2;   // total is now 30
const remainder = 17 % 5;  // 2 (17 divided by 5 leaves remainder 2)

Operator Precedence

Operators follow precedence rules — the same rules you learned in math class. Multiplication and division happen before addition and subtraction. Use parentheses to override the default order and to make your intent explicit:

const a = 2 + 3 * 4;       // 14 (multiplication first)
const b = (2 + 3) * 4;     // 20 (parentheses override)

The Math Object

JavaScript provides a built-in Math object with useful functions:

  • Math.round(x) — round to the nearest integer.
  • Math.floor(x) — round down. Math.ceil(x) — round up.
  • Math.max(a, b, c) / Math.min(a, b, c) — largest or smallest value.
  • Math.random() — a random decimal between 0 (inclusive) and 1 (exclusive).
  • Math.pow(base, exp) — exponentiation. Also written as base ** exp.

Floating-Point Precision

Computers store numbers in binary, and some decimal fractions cannot be represented exactly. This leads to surprising results:

0.1 + 0.2;   // 0.30000000000000004 (not exactly 0.3!)

This is not a JavaScript bug — it happens in nearly every language. For money or other precision-critical values, multiply by 100 and work in cents (integers), or use a dedicated decimal library.

Converting Strings to Numbers

Use Number(), parseInt(), or parseFloat() to convert text to a number. Always validate the result with Number.isNaN() before using it, because invalid input produces NaN (Not-a-Number), which silently propagates through calculations.

Example

              // Calculate a shopping cart total with tax
const prices = [12.99, 5.49, 3.00, 8.75];
const taxRate = 0.08;

let subtotal = 0;
for (const price of prices) {
  subtotal += price;
}

const tax = subtotal * taxRate;
const total = subtotal + tax;

// Round to 2 decimal places for display
const displayTotal = Math.round(total * 100) / 100;
console.log(`Subtotal: $${subtotal.toFixed(2)}`);
console.log(`Tax:      $${tax.toFixed(2)}`);
console.log(`Total:    $${displayTotal}`);

// Generate a random integer between 1 and 100
const random = Math.floor(Math.random() * 100) + 1;
console.log("Random number:", random);
            

This example sums prices, calculates tax, and rounds the result. toFixed(2) formats a number as a string with exactly 2 decimal places — useful for currency display.

Try it

  • Number Base Converter

    Convert numbers between binary, octal, decimal, and hexadecimal — see how the same value is represented in different bases.

  • Math Expression Evaluator

    Evaluate arithmetic expressions with proper operator precedence. Type formulas and see how precedence rules apply.

Common mistakes

The mistake

Trusting floating-point arithmetic for money calculations.

The fix

Work in integer cents (multiply by 100) or use a decimal library. Never store currency as floating-point dollars — rounding errors will accumulate.

The mistake

Forgetting that parseInt stops at the first non-digit character.

The fix

parseInt('42px') returns 42, which may hide invalid input. Always validate with Number.isNaN after conversion, or use Number() which returns NaN for invalid strings.

The mistake

Using == to compare numbers that might be strings.

The fix

Use === (strict equality). '5' == 5 is true (coercion), but '5' === 5 is false. Explicit conversion with Number() is safer than relying on coercion.

Related Cheatsheets

Practice Numbers and Math

11 exercises

Practice Numbers and Math

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors