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
Asked
Active
Viewed 1,683 times
2 Answers
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
-
You can also do `(t + 4) / 5 * 5` or `(t + n - 1) / n * n` more generally. – Peter Lawrey Nov 25 '18 at 17:30
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