Java Reference
In-Depth Information
Solution
If you simply cast a floating value to an integer value, Java truncates the value. A value like
3.999999 cast to an
int
or
long
becomes 3, not 4. To round floating-point numbers properly,
use
Math.round()
. It has two overloads: if you give it a
double
, you get a
long
result; if
you give it a
float
, you get an
int
.
What if you don't like the rounding rules used by
round
? If, for some bizarre reason, you
wanted to round numbers greater than 0.54 instead of the normal 0.5, you could write your
own version of
round()
:
public
public class
Round
{
/** We round a number up if its fraction exceeds this threshold. */
public
class
Round
public static
static final
final
double
double
THRESHOLD
=
0.54
;
/*
* Round floating values to integers.
* @return the closest int to the argument.
* @param d A non-negative values to be rounded.
*/
public
public static
static
int
int
round
(
double
double
d
) {
return
return
(
int
int
)
Math
.
floor
(
d
+
1.0
-
THRESHOLD
);
}
public
public static
static
void
void
main
(
String
[]
argv
) {
for
for
(
double
double
d
=
0.1
;
d
<=
1.0
;
d
+=
0.05
) {
System
.
out
.
println
(
"My way: "
+
d
+
"-> "
+
round
(
d
));
System
.
out
.
println
(
"Math way:"
+
d
+
"-> "
+
Math
.
round
(
d
));
}
}
}
If, on the other hand, you simply want to display a number with less precision than it nor-
mally gets, you probably want to use a
DecimalFormat
object or a
Formatter
object, which
we look at in
Formatting Numbers
.