views:

1519

answers:

4

Is there any way to round up decimal value to its nearest 0.05 value in .Net?

Ex:

7.125 -> 7.15

6.66 -> 6.7

If its now available can anyone provide me the algo?

+13  A: 

How about:

Math.ceiling(myValue * 20) / 20
Adam Bellaire
Excellent... Thanks
Prashant
predator4: That seems to be what the OP wants, with the `6.66 -> 6.7` example.
caf
@predator4: Its correct in my scenario (Tax calculation)
Prashant
Sorry. Fair enough, I've missunderstood the round up thing. To reduce confusion I've deleted my comment.
It should be noted that while this is a very good solution for the problem of rounding to arbitrary fractions, for decimal place rounding Math.Round should be used (just in case anyone comes looking at this question for a solution to more standard rounding).
ICR
Just as a warning, this can go wrong if the input is within a factor of 20 of the max value of a decimal (so, greater than about 4*10^27 for the decimal type). You can get around this by subtracting Math.floor, rounding the non-integer part, and then adding it back to the floor value. But since the original questioner's use is for a tax calculation, I doubt it matters unless it has to work in Zimbabwe...
Steve Jessop
+2  A: 

Duplicated here and here for ruby and python. It shouldn't be too different.

pavium
A: 

Have you looked at what's available from the static Math class?

Chuck Conway
+2  A: 

Math..::.Round Method (Decimal, Int32, MidpointRounding)

Rounds a double-precision floating-point value to the specified number of fractional digits. A parameter specifies how to round the value if it is midway between two other numbers.

   Math.Round(1.489,2,MidpointRounding.AwayFromZero)
Fredou