C# 如何将此科学记数法转换为十进制?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17587588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:55:57  来源:igfitidea点击:

How to convert this scientific notation to decimal?

c#decimal

提问by ControlPoly

After search in google, using below code still can not be compiled:

在谷歌搜索后,使用以下代码仍然无法编译

decimal h = Convert.ToDecimal("2.09550901805872E-05");   

decimal h2 = Decimal.Parse(
  "2.09550901805872E-05", 
   System.Globalization.NumberStyles.AllowExponent);

采纳答案by ControlPoly

Decimal h2 = 0;
Decimal.TryParse("2.005E01", out h2);

回答by MarcinJuraszek

You have to add NumberStyles.AllowDecimalPointtoo:

您还必须添加NumberStyles.AllowDecimalPoint

Decimal.Parse("2.09550901805872E-05", NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint);

MSDNis clear about that:

MSDN对此很清楚:

Indicates that the numeric string can be in exponential notation. The AllowExponent flag allows the parsed string to contain an exponent that begins with the "E" or "e" character and that is followed by an optional positive or negative sign and an integer. In other words, it successfully parses strings in the form nnnExx, nnnE+xx, and nnnE-xx. It does not allow a decimal separator or sign in the significand or mantissa; to allow these elements in the string to be parsed, use the AllowDecimalPoint and AllowLeadingSign flags, or use a composite style that includes these individual flags.

指示数字字符串可以采用指数表示法。AllowExponent 标志允许解析的字符串包含一个以“E”或“e”字符开头的指数,后跟可选的正号或负号和一个整数。换句话说,它成功解析了 nnnExx、nnnE+xx 和 nnnE-xx 形式的字符串。 它不允许在有效数或尾数中使用小数分隔符或符号;要允许解析字符串中的这些元素,请使用 AllowDecimalPoint 和 AllowLeadingSign 标志,或使用包含这些单独标志的复合样式。

回答by Dmitry Bychenko

Since decimal separator("."in your string) can vary from culture to cultureit's safier to use InvariantCulture. Do not forget to allow this decimal separator (NumberStyles.Float)

由于小数点分隔符"."在您的字符串中)可能因文化而异因此使用InvariantCulture. 不要忘记允许这个小数点分隔符 ( NumberStyles.Float)

  decimal h = Decimal.Parse(
    "2.09550901805872E-05", 
     NumberStyles.Float | NumberStyles.AllowExponent,
     CultureInfo.InvariantCulture);

Perharps, more convenient code is when we use NumberStyles.Any:

Perharps,更方便的代码是当我们使用NumberStyles.Any

  decimal h = Decimal.Parse(
    "2.09550901805872E-05", 
     NumberStyles.Any, 
     CultureInfo.InvariantCulture);

回答by Damith

use System.Globalization.NumberStyles.Any

System.Globalization.NumberStyles.Any

decimal h2 = Decimal.Parse("2.09550901805872E-05", System.Globalization.NumberStyles.Any);

回答by shafi7468

decimal h = Convert.ToDecimal("2.09550901805872E-05");   
decimal h2 = decimal.Parse("2.09550901805872E-05", System.Globalization.NumberStyles.Any)