Java Reference
In-Depth Information
The ceil() Method
The
ceil()
method always rounds a number up to the next largest whole number or integer. So
10.01
becomes
11
, and
-9.99
becomes
-9
(because -9 is greater than -10). The
ceil()
method has
just one parameter, namely the number you want rounded up.
Using
ceil()
is different from using the
parseInt()
function you saw in Chapter 2, because
parseInt()
simply chops off any numbers after the decimal point to leave a whole number, whereas
ceil()
rounds the number up.
For example, the following code writes two lines in the page, the first containing the number
102
and the second containing the number
101
:
var myNumber = 101.01;
document.write(Math.ceil(myNumber) + "<br />");
document.write(parseInt(myNumber, 10));
The floor() Method
Like the
ceil()
method, the
floor()
method removes any numbers after the decimal point, and
returns a whole number or integer. The difference is that
floor()
always rounds the number
down. So if you pass
10.01
you will be returned
10
, and if you pass
-9.99
you will see
-10
returned.
The round() Method
The
round()
method is very similar to
ceil()
and
floor()
, except that instead of always rounding
up or always rounding down, it rounds up only if the decimal part is
.5
or greater, and rounds down
otherwise.
For example:
var myNumber = 44.5;
document.write(Math.round(myNumber) + "<br />");
Â
myNumber = 44.49;
document.write(Math.round(myNumber));
This code would write the numbers
45
and
44
to the page.
Summary of Rounding Methods
As you have seen, the
ceil()
,
floor()
, and
round()
methods all remove the numbers after a
decimal point and return just a whole number. However, which whole number they return depends on
the method used:
floor()
returns the lowest,
ceil()
the highest, and
round()
the nearest equivalent
integer. This can be a little confusing, so the following is a table of values and what whole number
would be returned if these values were passed to the
parseInt()
function, and
ceil()
,
floor()
,
and
round()
methods: