← Back to JavaScript, page 4

javascript-0067 · Easy fresher

How do Math.round, floor, ceil, and trunc differ, and how do you generate a random integer in a range?

floor rounds down, ceil rounds up, trunc removes the fraction, and round goes to the nearest integer with halves rounding up toward positive infinity. They differ for negative numbers. A random integer from min to max inclusive is Math.floor(Math.random() * (max - min + 1)) + min. Math.random is not secure and cannot be seeded, so tests and security code need other tools.

Full answer

The four rounding functions only agree for positive numbers.

  • Math.floor(x) returns the largest integer not greater than x, so -2.5 becomes -3.
  • Math.ceil(x) returns the smallest integer not less than x, so -2.5 becomes -2.
  • Math.trunc(x) drops the fractional part, moving toward zero, so -2.5 becomes -2.
  • Math.round(x) goes to the nearest integer and rounds a tie (.5) toward positive infinity, so 2.5 becomes 3 and -2.5 becomes -2.

Math.random() returns a float from 0 up to but not including 1. To get an integer from min to max, both included, scale it by the size of the range, floor it, and shift it: Math.floor(Math.random() * (max - min + 1)) + min. Using Math.round here would make the end values half as likely as the others.

To shuffle an array fairly, use the Fisher-Yates algorithm: walk from the end, swap each item with a random earlier or equal position. Sorting with a random comparator is biased and slow.

Math.random cannot be seeded, so tests that depend on it are not repeatable. For tests, inject a small seeded generator. For passwords, tokens, or anything security-related, use crypto.getRandomValues or crypto.randomUUID, since Math.random is predictable.

Other useful facts: Math.max() with no arguments is -Infinity, Math.max(...[]) too, and any NaN argument makes the result NaN.

javascript
for (const x of [2.5, -2.5, 2.4, -2.6]) {
  console.log(String(x).padStart(5), Math.floor(x), Math.ceil(x), Math.trunc(x), Math.round(x));
}

function randomInt(min, max, random = Math.random) {
  return Math.floor(random() * (max - min + 1)) + min;
}

let allInRange = true;
const seen = new Set();
for (let i = 0; i < 10000; i++) {
  const value = randomInt(1, 6);
  seen.add(value);
  if (value < 1 || value > 6 || !Number.isInteger(value)) allInRange = false;
}
console.log('all in range:', allInRange, 'sides seen:', [...seen].sort());

function mulberry32(seed) {
  return function () {
    seed |= 0;
    seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
const seeded = mulberry32(42);
console.log(Array.from({ length: 5 }, () => randomInt(1, 100, seeded)));

function shuffle(list, random = Math.random) {
  const copy = [...list];
  for (let i = copy.length - 1; i > 0; i--) {
    const j = Math.floor(random() * (i + 1));
    [copy[i], copy[j]] = [copy[j], copy[i]];
  }
  return copy;
}
console.log(shuffle([1, 2, 3, 4, 5], mulberry32(7)));

console.log(Math.max(), Math.min(), Math.max(1, NaN), Math.max(...[3, 9, 4]));
console.log(typeof crypto.randomUUID(), crypto.getRandomValues(new Uint8Array(4)).length);

Run with Node.js v24.22.1 as js-67.js; two runs gave identical output. Output: 2.5 2 3 2 3 -2.5 -3 -2 -2 -2 2.4 2 3 2 2 -2.6 -3 -2 -2 -3 all in range: true sides seen: [ 1, 2, 3, 4, 5, 6 ] [ 61, 45, 86, 67, 18 ] [ 4, 2, 3, 5, 1 ] -Infinity Infinity NaN 9 string 4

Key points

  • floor goes down, ceil up, trunc toward zero, round to nearest with ties toward +Infinity.
  • They differ for negative numbers.
  • Random integer in [min, max]: floor(random * (max - min + 1)) + min.
  • Fisher-Yates gives an unbiased shuffle; sort with a random comparator does not.
  • Math.random is not seedable and not secure; use crypto for security.

Common mistakes

  • Using Math.round to scale a random number and making the end values less likely.
  • Using Math.floor on negative numbers when truncation toward zero was intended.
  • Sorting with a random comparator to shuffle.
  • Using Math.random for tokens, passwords, or other security-related values.

Follow-ups

  • Why does arr.sort(() => Math.random() - 0.5) give a biased result?
  • How would you pick a random item from an array?
  • How would you pick items with different weights?

Tips

  • Lay out the negative-number cases in a small table; that is where answers usually go wrong.
  • Write the range formula and say why it uses floor and plus one.
  • Mention the security limit of Math.random and name crypto.getRandomValues.