Specifically in Java, how can I determine if a double
is an integer? To clarify, I want to know how I can determine that the double does not in fact contain any fractions or decimals.
I am concerned essentially with the nature of floating-point numbers. The methods I thought of (and the ones I found via Google) follow basically this format:
double d = 1.0;
if((int)d == d) {
//do stuff
}
else {
// ...
}
I'm certainly no expert on floating-point numbers and how they behave, but I am under the impression that because the double
stores only an approximation of the number, the if()
conditional will only enter some of the time (perhaps even a majority of the time). But I am looking for a method which is guaranteed to work 100% of the time, regardless of how the double
value is stored in the system.
Is this possible? If so, how and why?
The answer is no, because any integer which converts back and forth to the same value, actually represents the same integer value in double.
integers are numbers without decimals. double is a floating-point numbers with double precisions. integer uses the same size of memory to describe a value of a higher range.
double
can store an exact representation of certain values, such as small integers and (negative or positive) powers of two.
If it does indeed store an exact integer, then ((int)d == d)
works fine. And indeed, for any 32-bit integer i, (int)((double)i) == i
since a double can exactly represent it.
Note that for very large numbers (greater than about 2**52 in magnitude), a double will always appear to be an integer, as it will no longer be able to store any fractional part. This has implications if you are trying to cast to a Java long
, for instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With