I have a number on which I need to round up the last digit, either to 0 or 5.
Examples:
0, 1, 2
to 0
, for example 12 -> 103, 4, 5, 6, 7
to 5
, like 37 -> 358, 9, 0
to 0
, again like 59 -> 60I tried Math.ceil()
or Math.floor()
but those are not working. As I've found out those are for floating point numbers and can not be used for this problem.
Math.ceil
and Math.floor
are for floating-point numbers (like Double
s). There's no built-in function for what you want to do, but this should work
public static int round(int original) {
if original % 10 <= 2 {
return original - (original % 10)
} else if original % 10 <= 7 {
return original - (original % 10) + 5
}
return original - (original % 10) + 10
}
If you want it to work with negative numbers, use this:
public static int round(int original) {
if original % 10 <= 2 {
return original - (original % 10)
} else if original % 10 <= 7 {
return original - (original % 10) + 5
} else if original % 10 <= 9 {
return original - (original % 10) + 10
} else if original % 10 >= -2 {
return original - (original % 10)
} else if original % 10 >= -7 {
return original - (original % 10) - 5
}
return original - (original % 10) - 10
}
Clearly, you can't just copy & paste this code, because you'll need to put it in a class and possibly change the visibility and static
ness (the public static
) part.
To use it, call int rounded = round(input)
Hope this helps!