Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round *down* integers in Java?

Tags:

java

numbers

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
like image 981
Redandwhite Avatar asked Nov 23 '09 14:11

Redandwhite


People also ask

Does Java round up or down for integers?

The answer is Yes. Java does a round down in case of division of two integer numbers.

Does Java round 0.5 up or down?

It is used for rounding a decimal to the nearest integer. In mathematics, if the fractional part of the argument is greater than 0.5, it is rounded to the next highest integer. If it is less than 0.5, the argument is rounded to the next lowest integer.


3 Answers

Simply divide by 1000 to lose the digits that are not interesting to you, and multiply by 1000:

i = i/1000 * 1000

Or, you can also try:

i = i - (i % 1000)
like image 93
abyx Avatar answered Oct 18 '22 08:10

abyx


You could divide the number by 1000, apply Math.floor, multiply by 1000 and cast back to integer.

like image 23
Poindexter Avatar answered Oct 18 '22 09:10

Poindexter


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
like image 23
Alex - GlassEditor.com Avatar answered Oct 18 '22 10:10

Alex - GlassEditor.com