How to convert this scientific notation to decimal?

后端 未结 6 1135
误落风尘
误落风尘 2020-12-11 00:38

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

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

decimal h2 = Decima         


        
相关标签:
6条回答
  • 2020-12-11 00:51

    You have to add NumberStyles.AllowDecimalPoint too:

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

    MSDN is clear about that:

    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.

    0 讨论(0)
  • 2020-12-11 00:52

    This thread was very helpful to me. For the benefit of others, here is complete code:

    var scientificNotationText = someSourceFile;
    // FileTimes are based solely on nanoseconds.
    long fileTime = 0;
    long.TryParse(scientificNotationText, NumberStyles.Any, CultureInfo.InvariantCulture, 
    out fileTime);
    var dateModified = DateTime.FromFileTime(fileTime);
    
    0 讨论(0)
  • 2020-12-11 01:00

    Since decimal separator ("." in your string) can vary from culture to culture it's safier to use InvariantCulture. Do not forget to allow this decimal separator (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:

      decimal h = Decimal.Parse(
        "2.09550901805872E-05", 
         NumberStyles.Any, 
         CultureInfo.InvariantCulture);
    
    0 讨论(0)
  • 2020-12-11 01:05
    decimal h = Convert.ToDecimal("2.09550901805872E-05");   
    decimal h2 = decimal.Parse("2.09550901805872E-05", System.Globalization.NumberStyles.Any)
    
    0 讨论(0)
  • 2020-12-11 01:10
    Decimal h2 = 0;
    Decimal.TryParse("2.005E01", out h2);
    
    0 讨论(0)
  • 2020-12-11 01:16

    use System.Globalization.NumberStyles.Any

    decimal h2 = Decimal.Parse("2.09550901805872E-05", System.Globalization.NumberStyles.Any);
    
    0 讨论(0)
提交回复
热议问题