Evgeniy  Kozlov
Evgeniy Kozlov

Reputation: 119

c# convert string 4,60E+12 to int / int64

I have list string - "1,60E+12" - "2,60E+12" - "3,60E+12" - "8,60E+12" How convert this string to int / int64 ?

Upvotes: 0

Views: 302

Answers (1)

Andy Brown
Andy Brown

Reputation: 19171

Simple, you just need to use the <type>.Parse overload which specifies the number styles to allow the exponent:

int number = Int32.Parse(value, NumberStyles.AllowExponent);

And for a list of strings:

var numbers = values.Select(x => int.Parse(x, NumberStyles.AllowExponent)).ToList();

If your numbers have decimal points (also see the footnote for a shorter style), you'll need:

Int32.Parse(value, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint);

And, as your numbers appear to use a culture specific format (using , for a decimal point) you may also need to specify a format provider like so:

Int32.Parse(value, 
    NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint, 
    CultureInfo.GetCultureInfo("de-DE").NumberFormat);

If your numbers are too large then you'll need to use long instead of int otherwise you'll get an OverflowException.

There is no difference between the output from Int32.Parse and int.Parse. Stylistically I prefer the latter.


Footnote: You can get all the combined styles required to do a full exponent parse by simply specifying NumberStyles.Float. As per the docs this style ... indicates

that the AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign, AllowDecimalPoint, and AllowExponent styles are used. This is a composite number style.

Upvotes: 3

Related Questions