开发者

How to Parse a String to Double

Here is开发者_如何学运维 my string

  20.0e-6

I'm parsing it like

String Ans=Double.Parse("20.0e-6")

Now i'm getting the result like 2E-05 But the required output should be like 0.00002

How to get this?


The result of Double.Parse is a Double, not a string. You need to output a string from the double, using ToString.

You should also use an overload of Double.Parse that has a NumberStyles parameter. Using the Float value allows exponent notation:

string Ans=Double.Parse("20.0e-6", NumberStyles.Float).ToString("0.#####");

If you don't want to risk exceptions (InvlidCastException for example), you can use TryParse:

Double res;
if (Double.TryParse("20.0e-6", NumberStyles.Float, 
                    CultureInfo.InvariantCulture ,res))
{
  string Ans = res.ToString("0.#####");
}


It's the same number, but if you want to modify the output of the string, use a formatter on your ToString()

http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

So

String Ans=Double.Parse("20.0e-6").ToString("0.0####")


One way to get the result you want is to use String.Format as follow:

double x = 20.0e-6;

string y = string.Format("{0:0.######}",x);

Console.WriteLine(y);

Given your example, this outputs the value 0.00002

EDIT

I've just realised that this is actually the opposite of your question so in the aim of keeping the answer useful i'll add the following:

Given a string, you can parse as double and then apply the same logic as above. Probably not the most elegant solution however it offers another way to get the result you want.

string x = "20.0e-6";

var y = double.Parse(p);

Console.WriteLine(String.Format("{0:0.######}",y));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜