Search code examples
javaroundingcurrency

Rounding to multiples of 5


I'd like make my program to be even more precise and to consider that there aren't coins for 1,2,7 values (only 5,10,20,50,100..), so there is a rule called rounding to five forints.

Example:

111,112  -> 110 
113,114  -> 115
116,117  -> 115
118,119  -> 120

My question is which function should I use in JAVA to reach my goal and get the right rounded value?


Solution

  • You could write it this way:

    int roundTo5(int value)
    {
        return ((value + 2) / 5) * 5;
    }
    

    This takes any forint value, adds 2 and divides by 5. This makes a "floor rounding" of integers and multiplies 5 again.

    0 → 2 → 0 → 0
    1 → 3 → 0 → 0
    2 → 4 → 0 → 0
    3 → 5 → 1 → 5
    4 → 6 → 1 → 5
    5 → 7 → 1 → 5
    6 → 8 → 1 → 5
    7 → 9 → 1 → 5
    8 → 10 → 2 → 10
    9 → 11 → 2 → 10