Math and Random Numbers
Math is a built-in object that holds mathematical constants and functions: rounding, powers, roots, maximums, trigonometry and random numbers. You never create it with new; you call its functions directly, as in Math.round(4.6). The Fee Tracker uses Math to round amounts to cents, cap late fees, and (in its practice mode) pick random sample data.
In One Minute
- Rounding:
Math.round(nearest),Math.floor(down),Math.ceil(up),Math.trunc(drop decimals). Math.max(...values)andMath.min(...values)find extremes; spread an array into them.Math.sumPrecise(values)(ES2026) adds a list of numbers without accumulating rounding errors. As of November 2026 it runs in current Chrome, but Node.js 26 still needs a flag.Math.random()gives a decimal from 0 (inclusive) to 1 (exclusive). For an integer frommintomax:Math.floor(Math.random() * (max - min + 1)) + min.Math.randomis not secure. For tokens and passwords, usecrypto.getRandomValuesorcrypto.randomUUID.
Math Functions Table
| Function | Description |
|---|---|
Math.round(x) | It is used to round to the nearest integer (halves round up, toward +Infinity). |
Math.floor(x) | It is used to round down to the integer below. |
Math.ceil(x) | It is used to round up to the integer above. |
Math.trunc(x) | It is used to remove the fractional part (toward zero). |
Math.abs(x) | It is used to get the absolute (positive) value. |
Math.sign(x) | It is used to get -1, 0 or 1 depending on the sign. |
Math.max(...xs) / Math.min(...xs) | It is used to find the largest or smallest value. |
Math.pow(x, y) | It is used to raise x to the power y (same as x ** y). |
Math.sqrt(x) / Math.cbrt(x) | It is used to get the square or cube root. |
Math.hypot(...xs) | It is used to get the square root of the sum of squares. |
Math.sumPrecise(iterable) | It is used to add numbers with full precision (ES2026). |
Math.random() | It is used to get a pseudo-random decimal in [0, 1). |
Math.log(x) / Math.log10(x) / Math.log2(x) | It is used to get logarithms. |
Math.sin, Math.cos, Math.atan2... | It is used for trigonometry, in radians. |
Math.PI, Math.E | Constants: π and e. |
Rounding
const values = [4.4, 4.5, 4.6, -4.4, -4.5, -4.6];
for (const x of values) {
console.log(x, Math.round(x), Math.floor(x), Math.ceil(x), Math.trunc(x));
}4.4 4 4 5 4
4.5 5 4 5 4
4.6 5 4 5 4
-4.4 -4 -5 -4 -4
-4.5 -4 -5 -4 -4
-4.6 -5 -5 -4 -4Explanation: read the columns as round, floor, ceil, trunc.
Math.roundrounds halves up (toward positive infinity), so-4.5becomes-4, not-5. Many people expect "away from zero"; JavaScript doesn't do that.Math.flooralways goes down: for negatives, that means further from zero (-4.4becomes-5).Math.truncjust drops the decimals, so it goes toward zero for both signs.
Rounding to Decimal Places
Math.round rounds to whole numbers. To round to cents, scale up, round, and scale down:
const amount = 12.345;
console.log(Math.round(amount * 100) / 100);
console.log(Math.round(1.005 * 100) / 100);
console.log(Math.round((1.005 + Number.EPSILON) * 100) / 100);12.35
1
1.01The 1.005 case fails because 1.005 * 100 is 100.49999999999999 in binary. Adding a tiny Number.EPSILON nudges it over. In money code, the cleanest fix is to keep amounts in integer cents from the start, so there's nothing to round.
Max, Min and Clamping
const fees = [120, 85, 450, 45];
console.log(Math.max(...fees));
console.log(Math.min(...fees));
console.log(Math.max());
const clamp = (value, low, high) => Math.min(Math.max(value, low), high);
console.log(clamp(36, 0, 30));
console.log(clamp(-5, 0, 30));
console.log(clamp(12, 0, 30));450
45
-Infinity
30
0
12Math.max takes separate arguments, so ...fees spreads the array into them. With no arguments, Math.max() is -Infinity, which is easy to miss when an array is empty. The clamp helper keeps a value inside a range: here, a late fee between $0 and $30.
Math.sumPrecise (ES2026)
Adding decimals one by one lets rounding errors build up. Math.sumPrecise, new in ES2026, takes an iterable of numbers and returns their sum as if computed with unlimited precision, rounded only once at the end:
const values = [0.1, 0.2, 0.3];
console.log(values.reduce((sum, x) => sum + x, 0));
console.log(Math.sumPrecise(values));
console.log([1e20, 0.1, -1e20].reduce((sum, x) => sum + x, 0));
console.log(Math.sumPrecise([1e20, 0.1, -1e20]));0.6000000000000001
0.6
0
0.1Explanation: in the second example, adding 0.1 to 1e20 is lost entirely in normal arithmetic (the small value is below the big one's precision), so the loop ends at 0. Math.sumPrecise keeps it. Note that it can't make 0.1 itself exact; it only stops errors from accumulating. It throws a TypeError if any item isn't a number.
Support (checked November 2026): the output above was captured in Chromium 158, and Playwright's WebKit build also has the method. Node.js 26 doesn't turn it on yet: Math.sumPrecise is undefined there unless you start Node with the V8 flag --js-sum-precise. That is why this example has no Try it check against Node; in code that must run everywhere today, test for it first: typeof Math.sumPrecise === "function".
Random Numbers
Math.random() returns a decimal greater than or equal to 0 and less than 1. Scale and round it to get the range you need:
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const rolls = [];
for (let i = 0; i < 1000; i++) rolls.push(randomInt(1, 6));
console.log(Math.min(...rolls), Math.max(...rolls));
console.log(rolls.every((r) => Number.isInteger(r) && r >= 1 && r <= 6));1 6
trueExplanation: Math.random() * 6 gives a decimal from 0 up to (not including) 6. Math.floor turns that into 0 to 5, and + 1 shifts it to 1 to 6. The + 1 inside (max - min + 1) makes max itself possible. The checks print the same thing on every run, even though the rolls differ: after 1,000 rolls, both ends of the range appear.
| You want | Formula |
|---|---|
| Decimal in [0, 1) | Math.random() |
| Decimal in [min, max) | Math.random() * (max - min) + min |
| Integer from min to max (both included) | Math.floor(Math.random() * (max - min + 1)) + min |
| Random array item | arr[Math.floor(Math.random() * arr.length)] |
Secure Randomness
Math.random is pseudo-random: fast and fine for games and sample data, but predictable enough that an attacker can sometimes work out future values. For anything security-related (session tokens, password reset codes, IDs that must be unguessable), use the Web Crypto API, available in browsers and Node.js:
const id = crypto.randomUUID();
console.log(id.length, id[14]);
const bytes = new Uint32Array(1);
crypto.getRandomValues(bytes);
console.log(bytes[0] >= 0 && bytes[0] <= 4294967295);36 4
truerandomUUID() returns a random version 4 UUID such as 3b241101-e2bb-4255-8caf-4136c566a962; its 15th character is always 4, the version number. The example prints only the parts that never change.
In Practice
The Fee Tracker splits a yearly fee into monthly installments, rounding each down to whole cents and putting the leftover cents on the last payment, and caps a late fee:
function installments(totalCents, months) {
const base = Math.floor(totalCents / months);
const plan = Array(months).fill(base);
plan[months - 1] += totalCents - base * months;
return plan;
}
const plan = installments(135000, 12);
console.log(plan.map((c) => (c / 100).toFixed(2)).join(" "));
console.log("Sum matches:", plan.reduce((a, b) => a + b, 0) === 135000);
const lateFeeCents = (daysLate) => Math.min(Math.max(daysLate - 10, 0) * 200, 3000);
console.log(lateFeeCents(5), lateFeeCents(14), lateFeeCents(60));112.50 112.50 112.50 112.50 112.50 112.50 112.50 112.50 112.50 112.50 112.50 112.50
Sum matches: true
0 800 3000Common Mistakes
Using Math.floor to drop decimals from negatives. Math.floor(-4.5) is -5. Use Math.trunc.
Forgetting + 1 in a random range. Math.floor(Math.random() * (max - min)) + min never returns max.
Math.max(array) without spreading. It returns NaN. Use Math.max(...array).
Using Math.random for security. Use crypto.getRandomValues or crypto.randomUUID.
Practice
Challenge: Write pickWinner(names) that returns a random name from the array, and prove it never returns anything outside the array by calling it 500 times.
Show solution
function pickWinner(names) {
return names[Math.floor(Math.random() * names.length)];
}
const names = ["Navika", "Srihitha", "Advitha"];
const picks = new Set();
for (let i = 0; i < 500; i++) picks.add(pickWinner(names));
console.log([...picks].every((p) => names.includes(p)));
console.log(picks.size);true
3Key Takeaways
| Need | Code |
|---|---|
| Drop decimals | Math.trunc(x) |
| Round to cents | Math.round(x * 100) / 100 |
| Largest value | Math.max(...arr) |
| Keep in range | Math.min(Math.max(x, lo), hi) |
| Secure ID | crypto.randomUUID() |
Was this tutorial helpful?