JavaScript Numbers & Math

Rounding, random numbers, converting strings and the weird 0.1 + 0.2.

Lesson 9 of 56Beginner13 min read

JavaScript has one main number type that covers both whole numbers and decimals. Together with the built-in Math object, it lets you round prices, roll random dice, find the highest score and turn text into numbers you can calculate with.

Numbers come up in almost every project: basket totals, countdown timers, game scores, progress bars and percentages. This lesson covers the tools for each of those jobs, plus a couple of surprises that catch out nearly every beginner.

Rounding numbers

Method4.6 →4.3 →-4.6 →
Math.round()54-5
Math.floor() (down)44-5
Math.ceil() (up)55-4
Math.trunc() (removes decimals)44-4

For displaying values, num.toFixed(2) returns a string with exactly two decimal places: (9.5).toFixed(2) gives "9.50". Because the result is a string, do all your calculations first and call toFixed only when you show the value.

Useful Math methods

  • Math.max(3, 9, 2) gives 9 and Math.min(3, 9, 2) gives 2.
  • Math.abs(-7) gives 7, the distance from zero.
  • Math.sqrt(16) gives 4, and Math.pow(2, 3) gives 8 (or write 2 ** 3).
  • Math.PI is 3.14159…
  • Math.random() gives a random decimal from 0 up to, but not including, 1.

Generating random whole numbers

The well-known formula for a random whole number from min to max, including both ends, is:

JavaScript
Math.floor(Math.random() * (max - min + 1)) + min

So a dice roll is Math.floor(Math.random() * 6) + 1. Reading it from the inside out: Math.random() * 6 gives a decimal from 0 up to 6, Math.floor rounds it down to 0 to 5, and + 1 shifts the range to 1 to 6.

Converting text to numbers

  • Number("42") gives 42, but Number("42px") gives NaN.
  • parseInt("42px") gives 42, because it reads digits until it reaches something else.
  • parseFloat("3.5kg") gives 3.5.
  • +"7" gives 7. The plus sign in front is a shortcut for conversion.

Values from form fields and from the page are always strings, so convert them before doing maths. Number() is the safest choice when the whole value should be numeric.

NaN and Infinity

NaN stands for "Not a Number". It's the result of impossible maths such as "cat" * 2. Check for it with Number.isNaN(value), because NaN is the only value that isn't equal to itself. Dividing by zero, as in 1 / 0, gives Infinity rather than an error.

JavaScript Numbers Syntax

Number tools

Math.round(2.5);          // 3
Math.floor(Math.random() * 10); // 0 to 9
(3.14159).toFixed(2);     // "3.14"
Number("12");             // 12
parseInt("12px");         // 12
Number.isNaN(x);          // true/false

JavaScript Numbers Summary

  • JavaScript uses one number type for whole numbers and decimals.
  • Math.round, floor, ceil and trunc round in different ways; toFixed formats for display.
  • Math.floor(Math.random() * n) + 1 gives a random whole number from 1 to n.
  • Convert strings with Number(), parseInt() or parseFloat().
  • Watch for NaN and small decimal rounding errors.

JavaScript Numbers Examples

Each example runs in the page. Edit the code and press Run to see what changes.

Example 1

Rounding a bill

const bill = 47.8;
const tipPercent = 12.5;

const tip = bill * tipPercent / 100;
const total = bill + tip;

console.log("Tip:", tip);
console.log("Tip rounded:", Math.round(tip));
console.log("Total: £" + total.toFixed(2));
console.log("Round up to:", Math.ceil(total));
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 412.5% of the bill: 5.975.
  2. Line 8Nearest whole pound: 6.
  3. Line 9Exactly two decimals for display, which is ideal for prices.
  4. Line 10Round up for a generous total: 54.
Example 2

Dice and random picks

Run it several times. The results change each time.

const roll = Math.floor(Math.random() * 6) + 1;
console.log("🎲 You rolled", roll);

const snacks = ["crisps", "popcorn", "grapes", "cookies"];
const pick = snacks[Math.floor(Math.random() * snacks.length)];
console.log("Tonight's snack:", pick);

const scores = [42, 87, 65, 91, 70];
console.log("Best:", Math.max(...scores), "Worst:", Math.min(...scores));
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 1Math.random() * 6 is 0 to 5.999…, floor makes it 0 to 5, and + 1 gives 1 to 6.
  2. Line 5The same idea picks a random index in an array.
  3. Line 9...scores spreads the array into separate arguments.
Example 3

Converting and checking

console.log(Number("42"), Number("42px"));
console.log(parseInt("42px"), parseFloat("3.75 kg"));
console.log("cat" * 2);
console.log(Number.isNaN("cat" * 2));
console.log(0.1 + 0.2);
console.log((0.1 + 0.2).toFixed(2));
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 1Number is strict: any non-numeric character gives NaN.
  2. Line 2parseInt/parseFloat read as much as they can.
  3. Lines 3 to 4Impossible maths gives NaN; check it with Number.isNaN.
  4. Lines 5 to 6The floating-point surprise, and how to display it nicely.

Common JavaScript Numbers Mistakes

toFixed returns a string

Don't
const price = (9.999).toFixed(2); // "10.00" (a string)
console.log(price + 1);           // "10.001"
Do
const price = Number((9.999).toFixed(2));
console.log(price + 1); // 11

Use toFixed for display, not for further maths.

Random range off by one

Don't
Math.floor(Math.random() * 6); // 0 to 5, never 6
Do
Math.floor(Math.random() * 6) + 1; // 1 to 6

Comparing with NaN

Don't
if (value === NaN) { … } // never true!
Do
if (Number.isNaN(value)) { … }

NaN is the only value not equal to itself.

JavaScript Numbers in Real Projects

Numbers in real projects

Online shops round prices and calculate tax, games roll random loot and track high scores with Math.max, fitness apps convert units, and timers use Math.floor to turn seconds into minutes. Payment systems store money as whole pennies to avoid floating-point errors.

JavaScript Numbers Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Round 7.8 down and 7.2 up.

console.log(Math.(7.8)); // 7
console.log(Math.(7.2));  // 8
Predict the outputeasy

What does this print?

console.log(Math.round(3.5), Math.max(4, 11, 7));
Multiple choicemedium

Which expression gives a random whole number from 1 to 10?

Fix the bugmedium

The average should be 82.5 and display as Average: 82.50. Fix the bugs.

const scores = ["80", "85"];
const sum = scores[0] + scores[1];
const average = sum / scores.length;
console.log("Average:", average.toFixed(2));
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Logs "Average: 82.50"

JavaScript Numbers Quiz

4 questions to check what you learned.

  1. What does Math.random() return?

    • A whole number from 1 to 100
    • A decimal from 0 up to (but not including) 1
    • Always 0.5
    • A random string
  2. What does parseInt("25px") return?

    • NaN
    • 25
    • "25"
    • 25px
  3. What type does (5).toFixed(2) return?

    • number
    • boolean
    • string
    • NaN
  4. What does 0.1 + 0.2 === 0.3 evaluate to?

    • false
    • true
    • NaN
    • An error

JavaScript Numbers Challenge

Temperature report

Given the readings array:

  1. Log Max: 24.6 using Math.max(...readings)
  2. Log Min: 12.1 using Math.min(...readings)
  3. Calculate the average and log it with one decimal: Average: 18.4
const readings = [18.2, 24.6, 12.1, 19.4, 17.7];
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Logs "Max: 24.6"
  • Logs "Min: 12.1"
  • Logs "Average: 18.4"