-1

now I have 3 textboxes that the user can type in them his degrees and the average will be calculated and displayed in another textbox! I've made the result to show just two fractional digits by calling the Math.Round() Method This is my code:

double Sum = int.Parse(textBox1.Text) + int.Parse(textBox2.Text) + int.Parse(textBox3.Text);
double Avg =  Sum / 3;
textBox4.Text = Math.Round(Avg, 2).ToString();

My problem is whenever the average is equal to an integer number like 20, I want it to display 20.00

  • 4
    try `Avg.ToString("#.00")` – Zohar Peled Mar 29 '17 at 12:48
  • There is a wealth of information in MSDN on different string formats. Dates, times, currency, etc: https://msdn.microsoft.com/en-us/library/system.string.format(v=vs.110).aspx – Forklift Mar 29 '17 at 12:51
  • 3
    Possible duplicate of [Formatting a double to two decimal places](http://stackoverflow.com/questions/18418668/formatting-a-double-to-two-decimal-places) – Smartis Mar 29 '17 at 12:52
  • Have a look at http://stackoverflow.com/questions/16280069/show-two-digits-after-decimal-point-in-c – Kai Adelmann Mar 29 '17 at 12:53
  • Possible duplicate of [Show two digits after decimal point in c++](http://stackoverflow.com/questions/16280069/show-two-digits-after-decimal-point-in-c) – Kai Adelmann Mar 29 '17 at 12:55

1 Answers1

2

Since C# 6.0 you can use string interpolation to format variables into a string (in this case, format the number with two decimal places):

$"{Avg:.00}"

Alternatively, use string#Format:

string.Format("{0:.00}", Avg);

If you don't want to use either of those, you can use the ToString function with this parameter for that as mentioned in the comments:

Avg.ToString("0.00")
nbokmans
  • 5,151
  • 3
  • 33
  • 54