-2

Can anyone help me to figure out how to make a code that rounds up a number to the nearest 5 or 10 in Java. For example : 4 becomes 5 1 becomes 5 8 becomes 10 48 becomes 50 43 becomes 45

Geert Bellekens
  • 12,788
  • 2
  • 23
  • 50
Godlixe
  • 103
  • 1
  • 5

2 Answers2

1

You can try this...

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int t;
    while(sc.hasNext()) {
        t = sc.nextInt();
        int x = t % 5 == 0 ? 0 : 1;
        System.out.println(((t/5) + x) * 5);
    }
}
Mukit09
  • 2,956
  • 3
  • 24
  • 44
0

Logic is simple, calculate remainder and increment value based on remainder value.

int x=11;
if(x%10>5) {
    x=x+(10-x%10);
}else if(x%10>0) {
    x=x+(5-x%5);
}
System.out.println(x);
Dark Knight
  • 8,218
  • 4
  • 39
  • 58