5

Possible Duplicate:
c# - How do I round a decimal value to 2 decimal places (for output on a page)

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.

0

2 Answers 2

16

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) 
Sign up to request clarification or add additional context in comments.

5 Comments

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?
Math.Round(1.479,2,MidpointRounding.AwayFromZero) round to 1.48
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, 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, 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.
3

Did you try

 Math.Round(16.482*200)/200; 

8 Comments

There isn't a cleaner way to do this?
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).
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, i tried that too. its not working on 16.425 or 16.124.
@Ramesh, did it work for the others?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.