Reputation: 142
I want to convert double values to int values in java. I am encountering the problem that simple casting doesn't work as I want and the Math.round() doesn't do it either.
My goal is that the doubles should be rounded down to the next smaller int. As following:
0.5 -> 0
1.7 -> 1
2.9 -> 2
-0.3 -> -1
-3.9 -> -4
The problem mostly are the different handling methods smaller than 0. Since I don't want them to round to the higher, but to the lower value.
Is there a java-native function for this, or how can I implement this effectively? I thought of the following, but I'd rather use a java-native function.
double d = -0.1D; // or whatever else
int i = (double) ((int) d) <= d ? (int) d : (int) d - 1;
Upvotes: 0
Views: 1916