I'd like to round integers down to their nearest 1000 in Java.
So for example:
- 13,623 rounds to 13,000
- 18,999 rounds to 18,000
- etc
I'd like to round integers down to their nearest 1000 in Java.
So for example:
int i = Math.floorDiv(-13623, 1000) * 1000
//i => -14000
The above code will always round down (towards negative infinity) assuming the divisor (1000 in the example) is positive.
The other answer (i = i/1000 * 1000) rounds down when i is positive, but up when i is negative.
-13623 / 1000 * 1000 == -13000
There is also a version of Math.floorDiv for longs which will work for very large numbers where the Math.floor method might fail due to the precision of double.
There are also Math.floorMod methods to go with the floorDivs which might allow you to shorten it a bit:
int i = -13623;
i -= Math.floorMod(i, 1000);
//i => -14000