Elapsed-time calculations
Convert a duration to completed whole seconds without counting a partial second.
JavaScript · Function
Math.floor() returns the largest integer less than or equal to a number. Unlike truncation, it rounds negative fractional values toward negative infinity.
Math.floor(x) converts its argument to a number and returns the greatest integer that is less than or equal to it. For negative fractional values, this moves toward negative infinity, so -5.05 becomes -6; integral values, infinities, and signed zero retain their corresponding values.
Math.floor(x)| Name | Type | Description |
|---|---|---|
x | number | The numeric value to floor. |
The largest integer less than or equal to x.
const values = [5.95, 5.05, -5.05, -0];
const floored = values.map((value) => Math.floor(value));
console.log(floored); // [5, 5, -6, -0]Maps each input to the greatest integer that does not exceed it.
Convert a duration to completed whole seconds without counting a partial second.
Turn a random decimal into an integer index or bounded integer.
Map a continuous numeric measurement to the lower discrete bucket.
Math.floor(x) returns the largest integer less than or equal to x. Consequently, positive fractional values move down toward zero, while negative fractional values move farther from zero toward negative infinity.
Follow-up: How does it differ from truncation for negative values? Math.floor(-5.05) is -6, whereas truncation removes the fraction toward zero and would produce -5.
Its signature is Math.floor(x), where x is a number. The returned value is the largest integer smaller than or equal to x, and the operation also handles special numeric values such as infinities and signed zero.
Follow-up: What happens for an integral input? The same number is returned because it already satisfies the floor condition.
Math.floor is useful when a calculation must produce an integer that never exceeds a quantity, such as converting elapsed milliseconds to completed seconds or selecting a zero-based random index. It is a static method, so it is accessed through Math.floor().
Follow-up: How would you select an inclusive random integer from min through max? Use Math.floor(Math.random() * (max - min + 1)) + min, assuming valid numeric bounds.
Math.ceil()Math.round()Math.trunc()Math.random()