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
| Method | 4.6 → | 4.3 → | -4.6 → |
|---|---|---|---|
Math.round() | 5 | 4 | -5 |
Math.floor() (down) | 4 | 4 | -5 |
Math.ceil() (up) | 5 | 5 | -4 |
Math.trunc() (removes decimals) | 4 | 4 | -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 andMath.min(3, 9, 2)gives 2.Math.abs(-7)gives 7, the distance from zero.Math.sqrt(16)gives 4, andMath.pow(2, 3)gives 8 (or write2 ** 3).Math.PIis 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:
Math.floor(Math.random() * (max - min + 1)) + minSo 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, butNumber("42px")givesNaN.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/falseJavaScript Numbers Summary
- JavaScript uses one number type for whole numbers and decimals.
Math.round,floor,ceilandtruncround in different ways;toFixedformats for display.Math.floor(Math.random() * n) + 1gives a random whole number from 1 to n.- Convert strings with
Number(),parseInt()orparseFloat(). - Watch for
NaNand small decimal rounding errors.
JavaScript Numbers Examples
Each example runs in the page. Edit the code and press Run to see what changes.
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));Line-by-line explanation
- Line 412.5% of the bill: 5.975.
- Line 8Nearest whole pound: 6.
- Line 9Exactly two decimals for display, which is ideal for prices.
- Line 10Round up for a generous total: 54.
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));Line-by-line explanation
- Line 1
Math.random() * 6is 0 to 5.999…,floormakes it 0 to 5, and+ 1gives 1 to 6. - Line 5The same idea picks a random index in an array.
- Line 9
...scoresspreads the array into separate arguments.
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));Line-by-line explanation
- Line 1
Numberis strict: any non-numeric character gives NaN. - Line 2
parseInt/parseFloatread as much as they can. - Lines 3 to 4Impossible maths gives NaN; check it with
Number.isNaN. - Lines 5 to 6The floating-point surprise, and how to display it nicely.
Common JavaScript Numbers Mistakes
toFixed returns a string
const price = (9.999).toFixed(2); // "10.00" (a string)
console.log(price + 1); // "10.001"const price = Number((9.999).toFixed(2));
console.log(price + 1); // 11Use toFixed for display, not for further maths.
Random range off by one
Math.floor(Math.random() * 6); // 0 to 5, never 6Math.floor(Math.random() * 6) + 1; // 1 to 6Comparing with NaN
if (value === NaN) { … } // never true!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.
Round 7.8 down and 7.2 up.
console.log(Math.(7.8)); // 7
console.log(Math.(7.2)); // 8
floor always goes down; ceil always goes up.What does this print?
console.log(Math.round(3.5), Math.max(4, 11, 7));Which expression gives a random whole number from 1 to 10?
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));- Logs "Average: 82.50"
+ joins them.JavaScript Numbers Quiz
4 questions to check what you learned.
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
What does
parseInt("25px")return?- NaN
- 25
- "25"
- 25px
What type does
(5).toFixed(2)return?- number
- boolean
- string
- NaN
What does
0.1 + 0.2 === 0.3evaluate to?- false
- true
- NaN
- An error
JavaScript Numbers Challenge
Temperature report
Given the readings array:
- Log
Max: 24.6usingMath.max(...readings) - Log
Min: 12.1usingMath.min(...readings) - Calculate the average and log it with one decimal:
Average: 18.4
const readings = [18.2, 24.6, 12.1, 19.4, 17.7];
- Logs "Max: 24.6"
- Logs "Min: 12.1"
- Logs "Average: 18.4"
reduce), divide by readings.length, then toFixed(1).