tags:

views:

116

answers:

4

I am working on a C# windows application. I have a label on my form that I want to display a calculation. Here is my code:

this.lblPercent.Text = (Convert.ToString(totalPercent));

I have the variable totalPercent defined as a double, how do I round this number to 2 decimal places?

When I run my program, 86.8245614 is being displayed in my application and I want it to display 86.82.

Susan

A: 

Here is the rounding method.

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

lblPercent.Text = Math.Round(totalPercent, 2).ToString();

Daniel A. White
totalPercent is a double value, so it needs to be cast to a decimal before it can be rounded..
Stuart Dunkeld
Thanks Daniel,I was on the right track, I just had the format wrong. Thanks for your help.Susan
Please vote up if you like.
Daniel A. White
A: 

You are probably looking for this:

public static string Format(string format, object arg0)
badp
+2  A: 

Or: String.Format("{0:0.00}", totalPercent);

See here for some examples of how to format numbers differently.

Rob Walker
+1  A: 

You can try this

' Gets a NumberFormatInfo associated with the en-US culture.
Dim nfi As NumberFormatInfo = New CultureInfo("en-US", False).NumberFormat

this.lblPercent.Text = totalPercent.ToString("P", nfi)

http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.numbergroupseparator(vs.71).aspx

GordyII