Reading history

JavaScript Numbers and Math: Rounding, toFixed, Random

4 min read 2 views

Learn JavaScript numbers and the Math object: toFixed, round, floor, ceil, max, sqrt, number checks, formatting and random integers in a range.

JavaScript has a single number type for whole numbers and decimals alike, plus a built-in Math object full of ready-made functions for rounding, powers, square roots and random numbers. This lesson shows how to format prices, round correctly, generate random integers for games and avoid the classic decimal surprises.

In this lesson you will learn

  • Rounding with toFixed, Math.round, floor, ceil and trunc
  • Useful Math functions such as max, abs and sqrt
  • Checking numbers with Number.isInteger and Number.isNaN
  • Formatting numbers with thousands separators
  • Random integers in a range

Rounding and the Math Object

const price = 1234.5678;
console.log(price.toFixed(2));            // "1234.57" (a string)
console.log(Math.round(price));           // 1235
console.log(Math.floor(price), Math.ceil(price), Math.trunc(-4.7));
console.log(Math.max(3, 9, 2), Math.min(3, 9, 2));
console.log(Math.abs(-12), Math.sqrt(81), Math.pow(2, 10));
console.log(Math.PI.toFixed(4));

console.log(Number.isInteger(5), Number.isInteger(5.5));
console.log(Number.isNaN(Number("hello")));
console.log(Number.MAX_SAFE_INTEGER);
console.log((1234567.891).toLocaleString("en-US"));
console.log(0.1 + 0.2 === 0.3, Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);

Output

1234.57
1235
1234 1235 -4
9 2
12 9 1024
3.1416
true false
true
9007199254740991
1,234,567.891
false true
  • toFixed(2) rounds to two decimal places but returns a string, ready for display. Convert it back with Number() if you need to calculate with it.
  • Math.round() goes to the nearest whole number, Math.floor() always goes down, Math.ceil() always goes up and Math.trunc() just drops the decimal part. They differ for negatives: Math.floor(-4.7) is -5 but Math.trunc(-4.7) is -4.
  • Math.max() and Math.min() take any number of arguments. For an array, spread it: Math.max(...arr).
  • Number.isInteger() and Number.isNaN() are reliable checks. Number.MAX_SAFE_INTEGER is the largest whole number stored exactly; use BigInt beyond it.
  • toLocaleString() adds thousands separators in the style of a given locale.
  • Decimal results such as 0.1 + 0.2 can be off by a tiny amount, so compare them with a small tolerance, or work in whole units such as paisa or cents.

Random Numbers

// Math.random() gives a decimal from 0 (inclusive) to 1 (exclusive)
function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Roll a die 6000 times and count each face
const counts = [0, 0, 0, 0, 0, 0];
for (let i = 0; i < 6000; i++) {
  counts[randomInt(1, 6) - 1]++;
}
const allClose = counts.every((c) => c > 850 && c < 1150);
console.log("Each face appeared roughly 1000 times:", allClose);

const colors = ["red", "green", "blue"];
const pick = colors[randomInt(0, colors.length - 1)];
console.log("Picked a valid colour:", colors.includes(pick));

Output

Each face appeared roughly 1000 times: true
Picked a valid colour: true
  • Math.random() returns a decimal from 0 up to (but never reaching) 1.
  • Multiply by the size of the range, round down with Math.floor and add the minimum. randomInt(1, 6) gives each of 1 to 6 with equal chance, as the 6000 rolls confirm.
  • Picking a random index from 0 to length - 1 selects a random array item.
  • The output prints checks rather than the raw numbers, because the numbers change on every run.
  • Math.random() is fine for games but not secure. For passwords or tokens use crypto.getRandomValues().

Math Cheat Sheet

FunctionExampleResult
Math.round(x)Math.round(2.5)3
Math.floor(x)Math.floor(2.9)2
Math.ceil(x)Math.ceil(2.1)3
Math.abs(x)Math.abs(-7)7
Math.sqrt(x)Math.sqrt(49)7
Math.max(...)Math.max(...[4, 8, 1])8
Math.random()Math.random()0 ≤ x < 1

Common Mistakes

  1. Doing maths on the result of toFixed(): "1.50" + 1 is "1.501".
  2. Using Math.round for random ranges, which makes the end values half as likely. Use Math.floor.
  3. Comparing decimals with === after arithmetic.
  4. Passing an array straight to Math.max: Math.max([1, 2]) is NaN; spread it.

Practice Exercises

Exercise 1. Work out the area of a circle with radius 7, rounded to 2 decimal places.

Show answer
console.log((Math.PI * 7 ** 2).toFixed(2)); // "153.94"

Exercise 2. Generate a random 4-digit OTP-style code as a string, such as “0482”.

Show answer
const code = String(Math.floor(Math.random() * 10000)).padStart(4, "0");
console.log(code);

For real one-time passwords, use crypto.getRandomValues() on the server instead.

Frequently Asked Questions

How do I round to 2 decimal places and keep a number?

Use Math.round(x * 100) / 100, or Number(x.toFixed(2)). Both give a number rather than a string.

How do I format a number as currency?

Use Intl.NumberFormat, for example new Intl.NumberFormat("en-IN", { style: "currency", currency: "BDT" }).format(1500).

Summary

  • All numbers share one type; toFixed formats them as strings.
  • round, floor, ceil and trunc round in different directions.
  • Math.floor(Math.random() * n) gives a random integer from 0 to n – 1.
  • Expect tiny decimal errors; round for display.

Next: JavaScript Dates and Times.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *