Click here to Skip to main content
15,888,301 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hallo everybody,

I discovered another weird malfunction of .NET:
Usually VS can handle the scientific notation. Like 'double a = 12.0e-6;' is interpreted as 0.000012.
But now I am trying to read this number from a file, so as a string. And in contrast to the correct result above, the function 'Convert.ToDouble("12.0e-6")' results in 0.00012! There is one zero missing respective it is too large by factor 10.
This happens regularly with all numbers (positive and negative) and all conversions.

Is there a reason why this fails in my program or does it always fail?
Do you know another way to convert these strings with .NET?


Thank you very much in advance!
Posted

There are a lot of different ways to convert values.
You could try double.TryParse:
C#
double val;
if (double.TryParse("12.0e-6", out val))
   {
   ...
   }

But...when I try your code, I get the right result. In fact, I get the same result regardless of what method I use.
C#
double a = 12.0e-6;
double b = Convert.ToDouble("12.0e-6");
double c;
if (double.TryParse("12.0e-6", out c))
    {

    }
Console.WriteLine("{0}\n{1}\n{2}\nAll same? {3}", a, b, c, a == b && a == c);
Gives me:
1.2E-05
1.2E-05
1.2E-05
All same?True
 
Share this answer
 
It 'fails' because in your application CultureInfo the dot ('.') is not recognized as decimal separator. Try, for instance:
double d = Convert.ToDouble("12.0e-6", System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
 
Share this answer
 
Comments
herrstress 23-Sep-15 5:43am    
This one I checked before. It fails the same way when it's only factor "12". The cultureInfo within the program is always en-US.
CPallini 23-Sep-15 5:50am    
On my system it (of course) produces the correct result (1.2E-5).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900