Is it possible to do this?
double variable;
variable = 5;
/* the below should return true, since 5 is an int.
if variable were to equal 5.7, then it would return false. */
if(variable == int) {
//do stuff
}
I know the code probably doesn't go anything like that, but how does it go?
Try this way,
for example:
hence 12.9 is not integer, nevertheless
hence 12.0 is integer
Personally, I prefer the simple modulo operation solution in the accepted answer. Unfortunately, SonarQube doesn't like equality tests with floating points without setting a round precision. So we have tried to find a more compliant solution. Here it is:
Remainder(BigDecimal)
returns aBigDecimal
whose value is(this % divisor)
. If this one's equal to zero, we know there is no floating point.Here's a solution:
Consider:
This sticks to core Java and avoids an equality comparison between floating point values (
==
) which is consdered bad. TheisFinite()
is necessary asrint()
will pass-through infinity values.Similar to SkonJeet's answer above, but the performance is better (at least in java):
you could try in this way: get the integer value of the double, subtract this from the original double value, define a rounding range and tests if the absolute number of the new double value(without the integer part) is larger or smaller than your defined range. if it is smaller you can intend it it is an integer value. Example:
If you assign to d the value 33.15 the method return true. To have better results you can assign lower values to testRange (as 0.0002) at your discretion.