Math.ceil, floor, and trunc Examples
Math.ceil
The general syntax for this method is:
Math.ceil(number)
This method rounds a decimal value UP to the next integer (hence the ceiling reference in the name). Integer values remain the same.
ceil
also operates on arrays.
Numerical strings can also be evaluated, but should be avoided as a best practice.
|
|
Console Output
9
9
-3
5
Math.floor
The general syntax for this method is:
Math.floor(number)
This method is the opposite of Math.ceil
. It rounds a decimal value DOWN to
the previous integer. Integer values remain the same.
floor
also operates on arrays.
Numerical strings can also be evaluated, but should be avoided as a best practice.
|
|
Console Output
8
8
-4
5
Math.trunc
The general syntax for this method is:
Math.trunc(number)
This method removes any decimals and returns only the integer part of number
.
trunc
also operates on arrays.
Numerical strings can also be evaluated, but should be avoided as a best practice.
|
|
Console Output
8
10
At first glance, Math.floor
and Math.trunc
appear to do exactly the
same thing. However, a closer look shows that the two methods treat negative numbers
differently.
|
|
Console Output
-16
-15
Combine with map
When combined with the map array method, ceil
, floor
, and trunc
will operate on each entry in an array. The syntax for this is:
arrayName.map(Math.method)
|
|
Console Output
[ -2, 4, -4, 9 ]
[ -2, 3, -5, 8 ]
[ -2, 3, -4, 8 ]