如何将科学记数法中的字符串转换为数字? [英] How can I convert a string in scientific notation into anumber?

查看:521
本文介绍了如何将科学记数法中的字符串转换为数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我发现了.NET的另一个奇怪的故障:

通常VS可以处理科学记数法。像'double a = 12.0e-6;'被解释为0.000012。

但是现在我试图从文件中读取这个数字,所以作为一个字符串。与上面的正确结果相反,函数'Convert.ToDouble(12.0e-6)'导致0.00012!有一个零缺少相应它太大了因子10.

这种情况​​经常发生在所有数字(正面和负面)和所有转换中。



我的程序中是否有这个失败的原因或它总是失败?

你知道用.NET转换这些字符串的另一种方法吗?





非常感谢您提前!

解决方案

转换值的方法有很多种。

您可以尝试double.TryParse:

  double  val; 
if double .TryParse( 12.0e-6 out val))
{
...
}



但是...当我尝试你的代码时,我得到了正确的结果。事实上,无论使用何种方法,我都会得到相同的结果。

  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} \ n全部相同?{3},a,b,c,a == b&& a == c);

给我:

 1.2E-05 
1.2E-05
1.2E-05
全部相同?是


它'失败'因为在您的应用程序中CultureInfo为点('。')不被识别为小数点分隔符。试试,例如:

 double d = Convert.ToDouble(12.0e-6,System.Globalization.CultureInfo.InvariantCulture.NumberFormat); 


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!

解决方案

There are a lot of different ways to convert values.
You could try double.TryParse:

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.

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


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);


这篇关于如何将科学记数法中的字符串转换为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆