I was trying to remove the fractional part from a double in case it is whole using:
(d % 1) == 0 ? d.intValue() : d
And encountered the following behavior which i don't understand:
public static void main(String[] args) {
Double d = 5D;
System.out.println((d % 1) == 0); // true
System.out.println((d % 1) == 0 ? d.intValue() : "not whole"); // 5
System.out.println((d % 1) == 0 ? d.intValue() : d); // 5.0
}
As you can see on the third line, the operator chooses the else value - 5.0 even though the condition (d % 1) == 0 is met.
What's going on here?
d.intValue()in both cases, it just performs conversions to make sure the second and third argument have the same type.double.