round() method, the
ceil() method and the
All of these are static methods of the
Math object. This means that they will be called directly via
Math.method_name(), not as a method of an instance of
Math object -
Math has no constructor.
Note: These methods can only be called on numbers, everything else will result in a
NaN value. The only exception is when it's called on
null - calling methods on
null will always return 0.
The ceil() Method
The name of this method is actually an abbreviation of the word ceiling - so its name automatically rings a bell that it rounds a number to the closest integer value larger than the current number.
If the number is an integer already - there's nothing to round, so it'll simply return the integer instead:
let x = 4.7 console.log(Math.ceil(x)) // Output: 5 let y = -3.2 console.log(Math.ceil(y)) // Output: -3 let z = "something not a number" console.log(Math.ceil(z)) // Output: NaN console.log(Math.ceil(null)) // Output: 0
ceil() when you specifically want to round to the next upper bound.
5.1 is rounded to
6, so if you want to round to the closest integer, you'll use the
round() function, covered in a later section of this guide.
The floor() Method
floor()'s method is also carefully chosen to fit its purpose. It rounds the integer to the closest integer smaller than the current one:
let x = 4.7 console.log(Math.floor(x)) // Output: 4 let y = -3.2 console.log(Math.floor(y)) // Output: -4 let z = "something not a number" console.log(Math.floor(z)) // Output: NaN console.log(Math.floor(null)) // Output: 0
The round() Method
round() method can be viewed as a two-in-one method, containing both
floor(). It rounds the number to the closest integer - it either "ceils" the number, or "floors" it, based on its value:
let x = 4.7 console.log(Math.round(x)) // Output: 5 let y = 4.2 console.log(Math.round(y)) // Output: 4 let z = 4.5 console.log(Math.round(z)) // Output: 5 console.log(Math.round(null)) // Output: 0
Everything up to x.49 will be rounded down to the lower value, while everything higher than that will be rounded to the higher value.
- Math.ceil() - rounds the number to a higher value
- Math.floor() - rounds the number to a lower value
- Math.round() - rounds the number to either lower or higher value, depending on the number
- When called with
nullas an argument, the methods always return 0
- When called with anything but a number or null as an argument, the methods always return