HTML and CSS Reference
In-Depth Information
Figure 9.24
The
Math
object, some properties and methods.
There are three
Math
methods available for rounding numbers up or down. They are the
ceil()
,
floor()
, and
round()
methods (see Table 9.7 for examples). The differences among the
methods might be confusing because all three methods truncate the numbers after the dec-
imal point and return a whole number. If you recall, JavaScript also provides the
parseInt()
function, but this function truncates the number after the decimal point, without rounding
either up or down.
The
ceil()
Method.
The
ceil()
method rounds a number
up
to the next largest whole
number and then removes any numbers after the decimal point; thus, 5.02 becomes 6
because 6 is the next largest number, and -5.02 becomes -5 because -5 is larger than -6.
The
floor()
Method.
The
floor()
method rounds a number
down
to the next lowest
whole number and then removes any numbers after the decimal point; thus, 5.02 now
becomes 5, and -5.02 becomes -6.
The
round()
Method.
The
round()
method rounds
up
only if the decimal part of the
number is .5 or greater. Otherwise, it rounds
down
to the nearest integer; thus, 5.5 is
rounded up to 6, and 5.4 is rounded down to 5.
Table 9.7
Rounding up and down
Number
ceil()
floor()
round()
2.55
3
2
3
2.30
3
2
2
-2.5
-2
-3
-2
-2.3
-2
-3
-2