1

As shown in the code, I have to convert the double value to string in order for the textbox to accept it. Now b = 0.60 but when I run the program the textbox only shows it as 0.6 not 0.60.

How can I make the textbox show the double value as it is? I mean to show the 2 numbers after the DOT.

private void button1_Click(object sender, EventArgs e)
{
    double b = 0.60;
    textBox1.Text = b.ToString();
}
pixelmeow
  • 654
  • 1
  • 9
  • 31
naouf
  • 627
  • 2
  • 18
  • 28

2 Answers2

6

double has an override of ToString which can take a format string, in your case you want 0.00 to force 2 decimal places:

private void button1_Click(object sender, EventArgs e)
{
    double b = 0.60;
    textBox1.Text = b.ToString("0.00");
}

Live example: http://rextester.com/VLA46480

Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • 1
    Just for other people's consideration, if you need a non-hardcoded string, you could perhaps [try something like this](http://stackoverflow.com/a/3726337/1189566) to figure out how many digits are to the left / right of the `.` and then use a loop to build your format string for you. Then pass that to `Double.ToString(string s)`. Another solution to get that count is [here](http://stackoverflow.com/questions/4483886/how-can-i-get-a-count-of-the-total-number-of-digits-in-a-number) but they both seem to have some limitations. – sab669 Nov 12 '15 at 16:30
1

You want to add formating as such:

double b = 0.60;
textBox1.Text = string.Format("{0:0.00}",b);

"{0:0.00}" indicates that it will show two numbers after a float point and following part 0:0 indicates that there can be as much numbers as there is before the floating point. It will round to bigger side.

Also with c# 6.0 you can use $:

textBox1.Text = $"{b.ToString("0.00")}";

Note: This method is not the best case solver at all. Just wanted to show you other ways of achieving same result and also to show the new feature of c# 6.0.

Karolis Kajenas
  • 1,523
  • 1
  • 15
  • 23
  • 1
    You might also want to explain what the `0` before the `:` means when using `String.Format()` as well. Looking at that, it's kind of confusing and not very explicit for a newer developer. – sab669 Nov 12 '15 at 16:32
  • @sab669 Edited. Hopefully it is a bit more clear now. – Karolis Kajenas Nov 12 '15 at 16:37