Search code examples
mathintegernumbersroundingnumber-formatting

Round up the last digit of whole numbers


I have a number on which I need to round up the last digit, either to 0 or 5.

Examples:

  1. From 0, 1, 2 to 0, for example 12 -> 10
  2. From 3, 4, 5, 6, 7 to 5, like 37 -> 35
  3. And from 8, 9, 0 to 0, again like 59 -> 60

I 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.


Solution

  • Math.ceil and Math.floor are for floating-point numbers (like Doubles). 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 staticness (the public static) part.

    To use it, call int rounded = round(input)

    Hope this helps!