Formatting Conversion from Double to String...

How do you get the conversion to show a particular number of decimal places?

For example:

double x = 100;

textBox1->Text = System::Convert::ToString(x);


This method will display "100" in the textbox but I would like it to display "100.00" in the textbox.

Any suggestions?

[422 byte] By [brenthellbent] at [2008-3-1]
# 1
I don't know how to do it with an IFormatProvider, but I do know how to do it with String::Format (http://msdn2.microsoft.com/en-us/library/fht0f5be.aspx):

textBox1->Text = String::Format("{0:N}", x);

Note that the above line will also append thousand separators for large numbers (eg. 1,000,000). Please take a look at the link for further information about the String::Format method.

OShah at 2007-9-8 > top of Msdn Tech,Visual Studio Express Editions,Visual C++ 2005 Express Edition...
# 2

OK, I found it with your help. Instead of

"{0:N}", x

I use

"{0:F4}", x

that gives me a decimal precision of 4.

But my next question is how do you make the precision dynamic so that it can be chosen at run time?

brenthellbent at 2007-9-8 > top of Msdn Tech,Visual Studio Express Editions,Visual C++ 2005 Express Edition...
# 3
The format string is just a string just concatenate the format string you want.

Something like this:
MyFormat = "{0:F" + int(myPrec).ToString() + "}";

MartinRichter at 2007-9-8 > top of Msdn Tech,Visual Studio Express Editions,Visual C++ 2005 Express Edition...