C# gurus: Help with String.Format() method.

Ok, I’ve got a form with a number of textboxes, and I’m trying to populate them with data in the form “123.0” using the following code snippet:



double V_In = Convert.ToDouble(OutputVNom.Text);
string value = Convert.ToString(V_In * 1.1);
VinHigh.Text = String.Format("{0:0.0}", value);


This is supposed to take text data from one textbox, do some math on it, output the result to another textbox and pad the value with a trailing 0 in the event it’s a round number. It calculates the value correctly and if the result has a remainder, it properly formats it with one decimal place (123.789 formats as 123.8), but if it’s an integer result, it doesn’t work (123.00 formats as 123, not 123.0). What am I doing wrong here? My understanding of the String.Format() method from here and other resources suggests this should work the way I want, but it ain’t. This is .NET C# under Visual Studio 2005.

You might try it with hash marks. Either way it looks borked up.

My suggestion if all else fails is to test for the presence of any decimal values and if not add 0.0000000001

Hm, looking at your code, I’m not sure what the second line is meant to be accomplishing? Why are you converting to a string, just to then format your temporary string as a number?


double V_In = Convert.ToDouble(OutputVNom.Text);
V_In *= 1.1;
VinHigh.Text = V_In.ToString("{0:0.0}");

^ Appears to be the preferred method. Certainly it means that you won’t be losing your double’s type when you go to format. But I admit to not knowing C#.

This turned out to be close. To format in the ToString() method, you don’t use (or, indeed, need) an index value, so I used:



V_In *= 1.1;
VinHigh.Text = V_In.ToString("0.0");


Which works perfectly. Thanks!

Then yeah, your problem was that you were trying to format a non-numeric (a string) as a numeric. In making it’s best guess at how to do that, it probably got confused and forgot to do some of the formatting.