You can use Math.round
to tell if a float
is an integer. (There are other approaches if your only purpose is to suppress the decimal point for integers when formatting as a string--see KevinO's comment.)
If f
is a float, Math.round(f)
returns an int
, which is f
rounded to the nearest integer, unless f
is outside the range of an int
. However, if f
is outside the range of an int
, then f
must be an integer, for all practical purposes--if f
is large enough that it is too big to fit in an int
, then it's too big to distinguish between values that are less than 1.0 apart (there are fewer bits of precision in a float
than in an int
). So there's no way for f
to represent a non-integer of that magnitude.
Given that, and assuming that f
isn't +/- infinity, you can test whether f
is an integer like this:
public boolean isInteger(float f) {
return f > (float)Integer.MAX_VALUE ||
f < (float)Integer.MIN_VALUE ||
f == (float)Math.round(f);
}
But please note that even a non-integer could appear as something.000000
when you format it, since the formatter will have to round f
to a certain number of decimal places when printing. It depends on what kind of format you're using.
NOTE: The above method is a correct way to determine whether a float is an integer, if the float
is the only information you have. However, in the context of a larger program, there are other considerations. If the parameter string is "2000000000.1"
, when you parse it as a float
you will get 2000000000, which is an integer, because the float
doesn't have enough precision to represent the .1
. At that point, your float
will be an integer value, and it's too late for it to know about the .1
--that information has been lost. If you don't want to lose that information, then don't use float
or double
--use BigDecimal
instead.