tags:

views:

286

answers:

2

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
+19  A: 

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)
abyx
+1: I never thought to use modulus this way. Also, you can shorten the line slightly by doing `i -= i % 1000` (dunno if parentheses are required around the right side or not)
R. Bemrose
Really? I always thought of modulus as a way to get the units of a number (`i % 10`) etc. Regarding the shortened version - that's probably what I'd do in my code, but wanted it to be clear here.
abyx
This rounds towards zero.
starblue
+3  A: 

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

Poindexter