string formatting question

T

Tenacious

Can anyone tell me why strSpd2 in the example below ends up being a
blank string when formatting a zero value? It would seem to me that
strSpd2 should end up being "0.0"

double val1 = 14.38009
double val2 = 0.0;
string strSpd1 = "";
string strSpd2 = "";


// This formats correctly. strSpd1 = "14.4"
strSpd1 = String.Format("{0:##.#}", val1);


// This does not format. strSpd2 = "" Why is this blank and not "0.0"
strSpd2 = String.Format("{0:#.#}", val2);
 
T

Tom Porterfield

Tenacious said:
Can anyone tell me why strSpd2 in the example below ends up being a
blank string when formatting a zero value? It would seem to me that
strSpd2 should end up being "0.0"

double val1 = 14.38009
double val2 = 0.0;
string strSpd1 = "";
string strSpd2 = "";


// This formats correctly. strSpd1 = "14.4"
strSpd1 = String.Format("{0:##.#}", val1);


// This does not format. strSpd2 = "" Why is this blank and not "0.0"
strSpd2 = String.Format("{0:#.#}", val2);

If you look at the documentation on formatting and the # format
character, you'll find the following information:

"Note that this specifier never displays the '0' character if it is not
a significant digit, even if '0' is the only digit in the string."

Use strSpd2 = String.Format("{0:0.0}", val2); instead.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top