Java Reference
In-Depth Information
Display 5.6
Some Methods in the Class
Math
(part 2 of 2)
public static long
round(
double
argument)
public static int
round(
float
argument)
Rounds its
argument
.
EXAMPLE
Math.round(3.2)
returns
3
;
Math.round(3.6)
returns
4
.
public static double
ceil(
double
argument)
Returns the smallest whole number greater than or equal to the
argument
.
EXAMPLE
Math.ceil(3.2)
and
Math.ceil(3.9)
both return
4.0
.
public static double
floor(
double
argument)
Returns the largest whole number less than or equal to the
argument
.
EXAMPLE
Math.floor(3.2)
and
Math.floor(3.9)
both return
3.0
.
public static double
sqrt(
double
argument)
Returns the square root of its
argument
.
EXAMPLE
Math.sqrt(4)
returns
2.0
.
The class
Math
has three similar methods named
round
,
floor
, and
ceil
. Some of
these return a value of type
double
, but they all return a value that is intuitively a
whole number that is close to the value of their arguments. The method
round
rounds
a number to the nearest whole number, and (if the argument is a
double
) it returns
that whole number as a value of type
long.
If you want that whole number as a value
of type
int
, you must use a type cast as in the following:
double
exact = 7.56;
int
roundedValue = (
int
)Math.round(exact);
You cannot assign a
long
value to a variable of type
int
, even if it is a value such as
8
,
which could just as well have been an
int
. A value such as
8
can be of type either
int
or
long
(or even of type
short
or
byte
) depending on how it was created.