CodeMIRAI
0 XP

Numbers and Math

4 min read 8 runnable examples Quiz included

Numbers are everywhere in programs: prices, scores, distances, timers, coordinates. JavaScript has one number type for whole numbers and decimals, a set of methods for formatting them, and a built-in Math object full of functions for rounding, comparing and random numbers. This lesson covers all of the everyday ones.

Writing numbers

JavaScript
const population = 1_400_000_000;   // _ separates digits for readability
const tiny = 2.5e-3;                // 2.5 x 10^-3 = 0.0025
const big = 3e6;                    // 3 x 10^6 = 3000000
const hex = 0xff, bin = 0b1010, oct = 0o17;
console.log(population, tiny, big);
console.log(hex, bin, oct);         // printed in ordinary base 10

The underscores in 1_400_000_000 are ignored by JavaScript; they only help you read the number. e means "times ten to the power of". Hexadecimal (0x), binary (0b) and octal (0o) are other ways to write the same whole numbers.

Rounding

The Math object has four ways to turn a decimal into a whole number. They differ in which way they go, which matters most for negative numbers:

FunctionDoes4.74.2-4.7-4.2
Math.round(x)nearest whole number (.5 goes up)54-5-4
Math.floor(x)down, towards minus infinity44-5-5
Math.ceil(x)up, towards plus infinity55-4-4
Math.trunc(x)cuts the decimals off44-4-4
JavaScript
console.log(Math.round(4.7), Math.round(4.5), Math.round(4.2));
console.log(Math.floor(4.7), Math.ceil(4.2), Math.trunc(4.7));
console.log(Math.floor(-4.2), Math.trunc(-4.2), Math.ceil(-4.7));

Typical uses: Math.floor for "how many full boxes" (Math.floor(20 / 6) is 3), Math.ceil for "how many boxes do I need" (Math.ceil(20 / 6) is 4).

Decimal places: toFixed

toFixed(n) rounds to n decimal places for display, and returns a string:

JavaScript
const price = 19.987;
console.log(price.toFixed(2), typeof price.toFixed(2));
console.log((5).toFixed(2));                     // "5.00": pads with zeros
console.log(Number(price.toFixed(1)) + 1);       // convert back to calculate

const rounded = Math.round(price * 100) / 100;   // a number, rounded to 2 places
console.log(rounded, typeof rounded);

Because toFixed gives text, adding to it joins instead of adding. Keep calculating with numbers and call toFixed only when you show the result.

Formatting for people

toLocaleString formats a number the way a country writes it. India groups digits as lakhs and crores (12,34,567), most other countries in thousands (1,234,567):

JavaScript
const amount = 1234567.891;
console.log(amount.toLocaleString("en-IN"));
console.log(amount.toLocaleString("en-US"));
console.log(amount.toLocaleString("de-DE"));      // Germany swaps . and ,

const rupees = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" });
console.log(rupees.format(amount));
const dollars = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
console.log(dollars.format(amount));
console.log((0.256).toLocaleString("en-IN", { style: "percent" }));

Checking numbers

JavaScript
console.log(Number.isInteger(5), Number.isInteger(5.5));
console.log(Number.isFinite(10 / 3), Number.isFinite(10 / 0));
console.log(Number.isNaN(Number("abc")));
console.log(Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER);

Largest, smallest and other Math functions

JavaScript
console.log(Math.max(4, 19, 7), Math.min(4, 19, 7));
const marks = [72, 91, 58, 86];
console.log(Math.max(...marks), Math.min(...marks));   // ... spreads an array into arguments

console.log(Math.abs(-12), Math.sign(-12), Math.sign(5));
console.log(Math.pow(2, 8), 2 ** 8);                   // the same
console.log(Math.sqrt(144), Math.cbrt(27));
console.log(Math.PI.toFixed(5), Math.hypot(3, 4));     // hypot: the long side of a right triangle
FunctionGives
Math.max(a, b, ...) / Math.min(...)the largest / smallest argument
Math.abs(x)the distance from zero (no minus sign)
Math.sign(x)-1, 0 or 1
Math.pow(a, b)a to the power b (same as a ** b)
Math.sqrt(x) / Math.cbrt(x)square root / cube root
Math.PI3.14159...
Math.hypot(a, b)the square root of a² + b²

Math.max(...marks) needs the ... (spread) because Math.max takes separate numbers, not an array: Math.max([1, 2]) is NaN.

Random numbers

Math.random() returns a random decimal from 0 up to, but not including, 1. Scaling and rounding it down gives a random whole number in any range:

JavaScript
console.log(Math.random());                          // e.g. 0.7302...

const dice = Math.floor(Math.random() * 6) + 1;      // 1 to 6
console.log("dice:", dice);

function randomInt(min, max) {                       // min to max, both included
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log("between 10 and 20:", randomInt(10, 20));

const colours = ["red", "green", "blue"];
console.log("random colour:", colours[Math.floor(Math.random() * colours.length)]);

const otp = String(randomInt(0, 999999)).padStart(6, "0");
console.log("one-time code:", otp);

How the dice line works: Math.random() * 6 is from 0 to just under 6; Math.floor makes it 0 to 5; + 1 makes it 1 to 6. Run it a few times and the numbers change.

Classic number programs

JavaScript
// area and circumference of a circle
const r = 7;
console.log("area:", (Math.PI * r ** 2).toFixed(2), "circumference:", (2 * Math.PI * r).toFixed(2));

// simple and compound interest on 10,000 at 8% for 3 years
const p = 10000, rate = 8, years = 3;
const simple = (p * rate * years) / 100;
const compound = p * (1 + rate / 100) ** years - p;
console.log("simple:", simple, "compound:", compound.toFixed(2));

// temperature conversion
const c = 37;
console.log(`${c}°C = ${(c * 9) / 5 + 32}°F`);

// the average of a list, to one decimal place
const scores = [72, 91, 58, 86];
const avg = scores.reduce((sum, s) => sum + s, 0) / scores.length;
console.log("average:", avg.toFixed(1));

Key points

  • One number type; _ separators and e notation make big and small numbers readable.
  • round (nearest), floor (down), ceil (up), trunc (cut off): they differ for negatives.
  • toFixed(n) returns a string for display; keep calculating with numbers.
  • toLocaleString("en-IN") and Intl.NumberFormat format numbers and currencies for people.
  • Math.max(...array) needs the spread; Math.floor(Math.random() * n) gives 0 to n - 1.

Practice

  1. Print Math.PI rounded to 0, 2 and 4 decimal places.
  2. A bus holds 42 people. How many buses do 250 people need? (Use the right rounding.)
  3. Write rollDice(n) that returns an array of n random dice rolls.
  4. Print 9876543.21 as Indian rupees and as US dollars.
  5. Find the hypotenuse of a right triangle with sides 5 and 12.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.