2

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

Aron Rotteveel
  • 81,193
  • 17
  • 104
  • 128

4 Answers4

2

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

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

Rob Walker
  • 46,588
  • 15
  • 99
  • 136
1

Here is the rounding method.

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

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

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • totalPercent is a double value, so it needs to be cast to a decimal before it can be rounded.. – stuartd Apr 19 '09 at 22:09
  • Thanks Daniel, I was on the right track, I just had the format wrong. Thanks for your help. Susan –  Apr 19 '09 at 22:11
1

You are probably looking for this:

public static string Format(string format, object arg0)
badp
  • 11,409
  • 3
  • 61
  • 89
1

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
  • 7,067
  • 16
  • 51
  • 69