Rounding integers to nearest multiple of 10

dhardy picture dhardy · Mar 1, 2013 · Viewed 45.9k times · Source

I am trying to figure out how to round prices - both ways. For example:

Round down
43 becomes 40
143 becomes 140
1433 becomes 1430

Round up
43 becomes 50
143 becomes 150
1433 becomes 1440

I have the situation where I have a price range of say:

£143 - £193

of which I want to show as:

£140 - £200

as it looks a lot cleaner

Any ideas on how I can achieve this?

Answer

evanmcdonnal picture evanmcdonnal · Mar 1, 2013

I would just create a couple methods;

int RoundUp(int toRound)
{
     if (toRound % 10 == 0) return toRound;
     return (10 - toRound % 10) + toRound;
}

int RoundDown(int toRound)
{
    return toRound - toRound % 10;
}

Modulus gives us the remainder, in the case of rounding up 10 - r takes you to the nearest tenth, to round down you just subtract r. Pretty straight forward.