What is the best way of determining if a given float(or double) has no significant decimal places.
f(234.0) = true f(34.45) = false f(3.1322) = false
ie equivalent of
EQ(((int)number) * 1.0 , number)
where EQ is a given method to compare floating points and it is OK to assume that the float fits in an integer.
Math.rint(x) == x
Math.rint()
returns a double
, so it also works for large numbers where the long
result of Math.round()
overflows.
Note that this also gives true for positive and negative infinity. You can explicitly exclude them by Math.rint(x) == x && !Double.isInfinite(x)
.
Round the value to the nearest integer, and calculate the absolute difference to the actual value.
If that difference is less than a certain percentage of the actual value you are close "enough".
You could try something like this:
public static boolean f(double d) {
return d % 1 == 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.