DanBrum
DanBrum

Reputation: 439

Double ToString() no scientific notation not returning a string for 0.0

I need to return the string representation of a double in decimal notation rather than scientific and I used a modified version of the accepted solution here:

Double ToString - No Scientific Notation

private static readonly string format = "." + new string('#', 324);
foo.ToString(format);

This works well other than for a value that equals zero i.e. 0, 0.0, 0.000 etc where it returns an empty string.

What would be the easiest way to return a string representing 0 for any value of zero.

I don't mind if the string is 0 or 0.0 etc as long as it is numerical and not scientific.

Edit: I know I could add a conditional statement to check if the string is empty but I am interested to see if there is a way to do it using string formatting.

Upvotes: 0

Views: 667

Answers (4)

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

try this:

  string format = "0." + new string('#', 324);

It will add zero before dot (if needed)

See example ideone

Upvotes: 1

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61952

Argh, those hacks people use. To give one hack more here:

foo.ToString(format + ";" + "-" + format + ";" + "0");

or with

static readonly string newFormat = format + ";" + "-" + format + ";" + "0";

defined under format in the code source, just:

foo.ToString(newFormat);

Of course that is a constant, so it is really:

foo.ToString(.####################################################################################################################################################################################################################################################################################################################################;-.####################################################################################################################################################################################################################################################################################################################################;0);

Hope you like it (I don't).

Upvotes: 0

Ivan Spahiyski
Ivan Spahiyski

Reputation: 86

Maybe it's what you are looking for:

        double aa = 12.33333;

        string foo = String.Format("{0:0.#}", System.Convert.ToSingle(aa));

Upvotes: 0

gleng
gleng

Reputation: 6304

You could always add a statement like:

foo.ToString(format)

if (string.IsNullOrEmpty(foo))
foo = "0";

Upvotes: 1

Related Questions