tags:

views:

568

answers:

5
+1  Q: 

C# - Math.Round

Hello,

I am trying to understand how to round to the nearest tenths position with C#. For instance, I have a value that is of type double. This double is currently set to 10.75. However, I need to round and then truncate everything past the tenths position. In this case, I am seeking a value of 10.8. How do I round to the tenths position in C#?

Thank you!

+10  A: 
Math.Round(yourNumber, 1)

The second parameter is number of decimal places to round to. In your case you want 1 decimal place as an end result.

Roatin Marth
+3  A: 

You simply need to use the overload of Math.Round that takes the decimals parameter.

Math.Round(10.75, 1) // returns 10.8

Just for comparison:

Math.Round(10.75)    // returns 11
Math.Round(10.75, 0) // returns 11
Math.Round(10.75, 2) // returns 10.75
Noldorin
+2  A: 

Do you really need to round it, or can you just format it for printing but allow the variable itself to hold its precision? Something like:

decimal value = 10.75;
value.ToString ("#.#");
Bill the Lizard
+5  A: 

Since you Used Math.Round() in your title, I'm going to assume you've already tried the basic Math.Round(10.75,1) approach and it returns something you don't expect. With that in mind, I suggest looking at some of the different overloads for the function, specifically one that accepts a MidPointRounding enum:

http://msdn.microsoft.com/en-us/library/f5898377.aspx

Joel Coehoorn
A: 

If you just want to "cut" everything after the first decimal, this shoudl work :

   return Math.Round(value * 10)/10
Toto