Sahil
Sahil

Reputation: 63

Converting double to string giving unexpected output

I have,

double d = 0.005;
d = d/100;
string str = Convert.ToString(d);

output of str = 5E-05

But I need output as 0.00005 While converting to string 0.00005 become 5E-05.

How can I resolve it?

Upvotes: 1

Views: 1600

Answers (3)

Sahil
Sahil

Reputation: 63

I found the solution :

 string str = d.ToString("F99").TrimEnd("0".ToCharArray());

It is working fine. But what exactly this is doing that I don't know. This working for dynamic double value.

Thnks for both of you, who replied.

Upvotes: 0

RedComet
RedComet

Reputation: 1202

You need a IFormatProvider:

http://www.csharp-examples.net/iformatprovider-numbers/
http://msdn.microsoft.com/en-us/library/7tdhaxxa.aspx

EDIT: The above poster give you more details.

using System;

namespace test1{
    class MainClass {
        public static void Main (string[] args)     {
            double d = 0.005;
            d = d/100;
            string str = String.Format("{0:0.#####}",d);
            Console.WriteLine ("The double converted to String:  "+str);
        }
    }
}

This should compile and show what you want.

It can't get any more clear than this

Edit: For more concrete examples look here: `

http://www.csharp-examples.net/string-format-double/

`

Upvotes: 1

rw.
rw.

Reputation: 11

You want to specify a format with which to convert the double to a string. Double.ToString does not let you do that (it uses scientific notation), so you should use String.Format, instead.

Here's your code, updated:

string str = String.Format("{0:0.#####}", 0.00005);

In fact, Double.ToString actually uses String.Format under the hood. See this link for more: MSDN docs about Double.ToString

Please see the following link for more examples of String.Format: Examples of using String.Format

Upvotes: 1

Related Questions