How to split a string into double

Here is my line

  20.0e-6

I take it apart

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

Now I get the result as 2E-05 But the required output should be similar to           0.00002

How to get it?

+3
source share
3 answers

The result Double.Parseis Double, not a string. You need to infer a string from double using ToString.

You should also use the overload Double.Parsethat has NumberStyles. Using a value Floatallows you to designate exponents:

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

If you do not want to risk exceptions (for example InvlidCastException), you can use TryParse:

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

, , ToString()

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

,

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

One way to get the desired result is to use it String.Formatas follows:

double x = 20.0e-6;

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

Console.WriteLine(y);

According to your example, this yields a value 0.00002

EDIT

I just realized that this is actually the opposite of your question, so in order to keep the answer useful, I will add the following:

Given a string, you can parse as double, and then apply the same logic as above. This is probably not the most elegant solution, but it offers another way to get the desired result.

string x = "20.0e-6";

var y = double.Parse(p);

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

Source: https://habr.com/ru/post/1778465/


All Articles