I'm trying to write a method which gets a double
, verifies if the number has something after the dot and if it does—returns a double
, if doesn't—returns an int
.
public class Solution {
public static void main(String[] args) {
double d = 3.000000000;
System.out.println(convert1(d));
System.out.println(convert2(d));
}
static Object convert1(double d) {
if(d % 1 == 0)
return (int) d;
else
return d;
}
static Object convert2(double d) {
return ((d%1) == 0) ? ((int) (d)) : d;
}
}
Output:
3
3.0
So, everything I want happens in method convert1()
, but doesn't happen in method convert2()
. It seems as these methods must do the same work. But what I have done wrong?