Math.ceil(), Math.floor(), and Math.round() - handle rounding in different ways:
Method | Description |
---|---|
Math.ceil() | rounds numbers up to the nearest integer value. |
Math.floor() | rounds numbers down to the nearest integer value. |
Math.round() | a standard round function, which rounds up if the number is at least halfway to the next integer value (0.5 or higher) and rounds down if not. |
The following example illustrates how these methods work:
console.log(Math.ceil(5.9)); console.log(Math.ceil(5.5)); console.log(Math.ceil(5.1)); console.log(Math.round(5.9)); console.log(Math.round(5.5)); console.log(Math.round(5.1)); console.log(Math.floor(5.9)); console.log(Math.floor(5.5)); console.log(Math.floor(5.1));
For all values between 5 and 6 (exclusive), Math.ceil() always returns 6, because it will always round up.
The Math.round() method returns 6 only if the number is 5.5 or greater; otherwise it returns 25.
Math.floor() returns 5 for all numbers between 5 and 6 (exclusive).