Java Reference
In-Depth Information
floor
and
ceil
The methods
floor
and
ceil
are similar to, but not identical to,
round
. Neither
one rounds, although they both yield a whole number that is close to their argument.
They both return a whole number as a value of type
double
(not of type
int
or
long
).
The method
floor
returns the nearest whole number that is less than or equal to
its argument. So
Math.floor(5.9)
returns
5.0
, not
6.0. Math.floor(5.2)
also
returns
5.0
.
The method
ceil
returns the nearest whole number that is greater than or equal to
its argument. The word
ceil
is short for “ceiling.”
Math.ceil(5.1)
returns
6.0
, not
5.0
.
Math.ceil(5.9)
also returns
6.0
.
If you want to store the value returned by either
floor
or
ceil
in a variable of type
int
, you must use a type cast as in the following example:
double
exact = 7.56;
int
lowEstimate = (
int
)Math.floor(exact);
int
highEstimate = (
int
)Math.ceil(exact);
Math.floor(exact)
returns the
double
value
7.0
, and the variable
lowEstimate
receives the
int
value
7. Math.ceil(exact)
returns the
double
value
8.0
, and the
variable
highEstimate
receives the
int
value
8
.
Because values of type
double
are effectively approximate values, a safer way to
compute the floor or ceiling as an
int
value is the following:
double
exact = 7.56;
int
lowEstimate = (
int
)Math.round(Math.floor(exact));
int
highEstimate = (
int
)Math.round(Math.ceil(exact));
This way, if
Math.floor(exact)
returns slightly less than
7.0
, the final result will still
be
7
and not
6
, and if
Math.ceil(exact)
returns slightly less than
8.0
, the final result
will still be
8
and not
7
.
The class
Math
also has the two predefined constants
E
and
PI
. The constant
PI
(often written
Math
constants
in mathematical formulas) is used in calculations involving circles,
spheres, and other geometric figures based on circles.
PI
is approximately
3.14159
. The
constant
E
is the base of the natural logarithm system (often written
e
in mathematical
formulas) and is approximately
2.72
. (We do not use the predefined constant
E
in this
text.) The constants
PI
and
E
are defined constants , as described in Chapter 1 . For
example, the following computes the area of a circle, given its radius:
area = Math.PI * radius * radius;
Notice that because the constants
PI
and
E
are defined in the class
Math
, they must
have the class name
Math
and a dot before them. For example, in Display 5.7, we have
redone the program in Display 5.2, but this time we used the constant
Math.PI
instead
of including our own definition of
PI
.