Core Rounding and Random Methods
Math.ceil()rounds upwards to the nearest integer.Math.floor()rounds downwards to the nearest integer.Math.round()performs standard rounding to the closest integer.Math.random()generates a pseudo-random decimal between 0 (inclusive) and 1 (exclusive), for instance, 0.483210945.
Generating Integer Ranges
Different combinations of these methods produce varying distributions:
Math.ceil(Math.random() * 10)yields integers from 1 to 10, though the chance of returning 0 is near impossible, making it poorly distributed.Math.round(Math.random())evenly distributes between 0 and 1.Math.floor(Math.random() * 10)evenly distributes integers from 0 to 9.Math.round(Math.random() * 10)yields integers from 0 to 10, but with unequal probability at the boundaries. The likelihood of returning 0 or 10 is half that of other numbers. This occurs because rounding to 0 only happens for values 0.0 to 0.4, whereas 1 is produced from 0.5 to 1.4, creating a smaller range for the extremes.
Custom Range Functions
A simple random integer from 0 to 10:
function generateBaseInteger() {
return Math.round(Math.random() * 10);
}
console.log(generateBaseInteger());A random floating-point number between two bounds:
function generateRandomFloat(floor, ceil) {
return Math.random() * (ceil - floor) + floor;
}
console.log(generateRandomFloat(1, 5));A random integer where the lower bound is inclusive and the upper bound is exclusive:
function generateRandomExclusiveUpper(floor, ceil) {
const min = Math.ceil(floor);
const max = Math.floor(ceil);
return Math.floor(Math.random() * (max - min)) + min;
}
console.log(generateRandomExclusiveUpper(1, 5));A random integer where both bounds are inclusive:
function generateRandomInclusive(floor, ceil) {
const min = Math.ceil(floor);
const max = Math.floor(ceil);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(generateRandomInclusive(1, 5));IEEE 754 Precision and Rounding
JavaScript numbers follow the IEEE 754 floating-point standard, utilizing the "round-to-nearest-even" mode. Consequently, the mathematical boundaries of the custom functions above are not perfectly absolute. When dealing with extremely large limits (2^53 or higher), the typically excluded upper bound might occasionally be returned due to precision limits.
The "round-to-nearest-even" rule differs from traditional half-up rounding. When a value lies exactly halfway between two integers, it is rounded to the nearest even integer.
Math.round(0.5)evaluates to 0.Math.round(1.5)evaluates to 2.Math.round(2.5)evaluates to 2.Math.round(3.5)evaluates to 4.
This "banker's rounding" ensures that an even digit is always the result when the fractional component is precisely 0.5. The toFixed() method also exhibits this behavior:
const numA = 1.55;
const numB = 1.65;
const strA = numA.toFixed(1);
const strB = numB.toFixed(1);
console.log(strA);
console.log(strB);