Convert double to string

  • Thread starter Thread starter Laurence
  • Start date Start date
L

Laurence

I want to convert a double value to string.

1.2345678911 -> "1.234567891"
123 -> "123"

I used the following code to convert it:

string str = doubleValue.ToString("f9");

but the second value is converted to "123.000000000".

So I changed the code to:


string str = doubleValue.ToString("f9").TrimEnd('0').TrimEnd('.');


It works fine.

But I want to know if there is a better solution. Could anybody give me a
format string so I can use the following code to do the same thing as above?

string str = doubleValue.ToString(formatString);
 
Laurence said:
I want to convert a double value to string.

1.2345678911 -> "1.234567891"
123 -> "123"

I used the following code to convert it:

string str = doubleValue.ToString("f9");

but the second value is converted to "123.000000000".

So I changed the code to:


string str = doubleValue.ToString("f9").TrimEnd('0').TrimEnd('.');


It works fine.

No it doesn't - try giving it "1230" and you'll get back "123".
But I want to know if there is a better solution. Could anybody give me a
format string so I can use the following code to do the same thing as above?

string str = doubleValue.ToString(formatString);

Try "0.#########" as the format string. I think that does what you
want.
 
Great. Thank you.
Jon Skeet said:
No it doesn't - try giving it "1230" and you'll get back "123".


Try "0.#########" as the format string. I think that does what you
want.
 
Back
Top