Recently I ran into an interesting problem on a small project I was working on. The problem was on the surface fairly simple. Take a currency amount and round it up to the nearest 0.05. While the solution is not earth shattering it took long enough to figure out that I figured it was worth recording for my future self.
The first part of the problem is to round to 0.05 which is accomplished by doing this (thanks Google..):
decimal initialValue = 0.56;
decimal value = Math.Round(initialValue / 5, 2) * 5;
But the problem is this code will actually round to the nearest 0.05 as opposed to only rounding up. So 0.62 will round to 0.60 where as our requirement is to round to 0.65.
But that part of the problem is actually fairly easy to solve..
if((value - initialValue) < 0)
value += 0.05m;
And there you have it. We can now round up to the nearest 0.05.
posted @ Sunday, October 04, 2009 12:43 AM