1

I haven't found any answer of this. But I want to round up to ten of any number. Like this:

32 -> 40
25 -> 30
88 -> 90

But with this code below I get rounded down. How can I always round up and not to the nearest ten?

Math.round(number / 10.0) * 10;
Jedrod
  • 13
  • 4

4 Answers4

4

See my previous answer to another question for how to handle negative numbers.

To round down to nearest multiple of 10, simply divide by 10 and multiply by 10, using the fact that integer division always rounds down (towards zero).

roundDown = value / 10 * 10;

To round up, add 9 before rounding down.

roundUp = (value + 9) / 10 * 10;

To round half-up, add 5 before rounding down.

roundHalfUp = (value + 5) / 10 * 10;

Test

System.out.println("    Down  Up  Half-Up");
int[] arr = { 32, 25, 88, 50 };
for (int v : arr)
    System.out.printf("%2d %4d %4d %5d%n", v, v / 10 * 10, (v + 9) / 10 * 10, (v + 6) / 10 * 10);

Output

    Down  Up  Half-Up
32   30   40    30
25   20   30    30
88   80   90    90
50   50   50    50
Andreas
  • 154,647
  • 11
  • 152
  • 247
2

round may round up or down, depending on the remainder. Instead, you should use ceil:

Math.ceil(number / 10.0) * 10
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

Mathematically you want a value plus the difference from ten of the remainder. You can get the remainder with % (modulus). Like,

int[] arr = { 32, 25, 88 };
for (int v : arr) {
    System.out.printf("%d -> %d%n", v, v + (10 - (v % 10)));
}

Outputs (as requested)

32 -> 40
25 -> 30
88 -> 90

You said always rounding up. If ninety should stay ninety, then you test for a remainder of zero. Like,

for (int v : arr) {
    int r = v % 10;
    if (r != 0) {
        System.out.printf("%d -> %d%n", v, v + 10 - r);
    } else {
        System.out.printf("%d -> %d%n", v, v);
    }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

You can do it by using only Java integer arithmetic with this:

x % 10 == 0 ? x : ((x / 10)  + 1) * 10

so:

int x = 41;
int r = x % 10 == 0 ? x : ((x / 10)  + 1) * 10;
System.out.println(r);

will print:

50
forpas
  • 160,666
  • 10
  • 38
  • 76