Question

I have the following code that I think should format the string to have four decimal places. (The intent is for a value of 3.59, add trailing zeros so the string value becomes 3.5900)

string   PreFC = string.Format(dr.Cells["Price"].Value.ToString(),"{0:n4}");
                       // PreFC = (dr.Cells["Price"].Value.ToString());

                        StringBuilder FC = new StringBuilder(PreFC);
                        MessageBox.Show(PreFC);

This doesn't work. The value it gives me is 3.59 instead of 3.5900. What am I doing wrong?

Was it helpful?

Solution

You have misplaced format and value it should be:

string   PreFC = string.Format("{0:n4}", dr.Cells["Price"].Value);
                            //Format should be first

Don't call ToString on Value, You will not get the numeric format to work on string values. Instead just pass dr.Cells["Price"].Value, since string.Format accepts object type parameter

OTHER TIPS

See Standard Numeric Format Strings

For "Precision specifier" use "f"

string PreFC = ((double)dr.Cells["Price"].Value).ToString("f");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top