views:

258

answers:

2

Hi,

How to round decimal value up to nearest 0.05 value??, the linked SO post also discusses the similar topic, but its not the output i expected.

I need to convert the decimal values like this

16.489-->16.49
16.482-->16.48
16.425-->16.43
7.67 --> 7.67 (no conversion)

I can use the below C# method to convert the values

  Math.Round(16.482*20)/20;

But this method not works for me, it gives the following results

16.489-->16.5 
16.482-->16.5 
7.67 --> 7.7
16.425-->16.45 

whats the elegant way in c# to do this.

Cheers

Ramesh Vel

+2  A: 

Did you try

 Math.Round(16.482*200)/200;
Anthony
There isn't a cleaner way to do this?
Ben S
I have no idea, I don't know C#. I just know how the example code works. It just multiples the number by the inverse of where you want to round, and then divides that sum by the same inverse to get back to the same number. You can use the same idea to round to the nearest quarter (which is how I learned this trick).
Anthony
You could create a function that you plug the value and what you want to round off to, but since the SO didn't seem to realize that he wants to round off to .005, I'm not sure that would have been helpful to suggest.
Anthony
@Anthony, i tried that too. its not working on 16.425 or 16.124.
Ramesh Vel
@Ramesh, did it work for the others?
Anthony
@Anthony, yes it works on other scenarios..
Ramesh Vel
I see, you want to round to the nearest .01, not .05 or .005. So you should do `Math.Round(16.482*100)/100;`. Let me know if that gives trouble.
Anthony
@Anthony, yes it works now after specifying 100. thanks
Ramesh Vel
+3  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
What if you want to round to the nearest quarter? so that 1.489 rounds to 1.5, but 1.479 rounds to 1.475?
Anthony
Math.Round(1.479,2,MidpointRounding.AwayFromZero) round to 1.48
Fredou
@Fredou, it works fine.. thanks...
Ramesh Vel
But I don't want to round to 1.48 in that example, I wan to round to 1.475. I want the last two digits to round to 0, 25, 5, or 75, depending on what is closest.
Anthony
@anthony, I'm half asleep but... this should do it ? (decimal)(int)(decimal)(1.479*100)/100+(Math.Round((decimal)1.479,2,MidpointRounding.AwayFromZero) - (decimal)1.479 )/2*10
Fredou
Fredou, Hey man, I really appreciate the time. I was really trying to make a case for using the inverse method that the user was originally trying to use and that I was showing how to adapt. But I'm really blown away that you figured that out. Get some sleep, buddy.
Anthony