3

I'm getting an exception when trying to parse a number that is in scientific notation. Looking at other posts on how to do it, and I can't tell what I'm doing any differently than those.

I've tried the following:

System.Convert.ToInt64("1.0206e+06");

System.Convert.ToInt64("1.0206E+06");  // Uppercase 'E'

These result in a FormatException: Input string was not in the correct format.

I tried these:

Int64.Parse("1.0206e+06", System.Globalization.NumberStyles.Any);

Int64.Parse("1.0206e+06", System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture);

Int64.Parse("1.0206e+06", System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture);

These all result in an OverflowException: Value was too large or too small.

Also tried with Int32.Parse and got the same exception and message:

(long)Int32.Parse(str, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture);

Using Decimal.Parse works with the same string and parameters passed to it:

(long)Decimal.Parse(str, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture);

This answer suggests using this:

Double.Parse("1.234567E-06", System.Globalization.NumberStyles.Float);

Which is similar to my last example, I just accept all number styles, and that answer used a negative exponent. In fact, I fed that exact string into my examples and I still get the same exceptions.

Not sure if it matters, but I'm using Mono C#, the version that comes with Unity.

Here's the C# source file: https://github.com/Unity-Technologies/mono/blob/unity-staging/mcs/class/corlib/System/Int64.cs. The exception is thrown on line 469 and doesn't provide me a call stack before that point. But I'm guessing the exception is created on line 355 or 372 since those match the exception type and message I'm being shown.

Community
  • 1
  • 1
Nic Foster
  • 2,864
  • 1
  • 27
  • 45

1 Answers1

0

I'm going to assume that this is a bug with the version of Mono C# I'm using, which comes with Unity 5.5.x or earlier. Their repository can be found here.

Their implementation of Int64.Parse does not even check for the NumberStyles.AllowExponents flag, or handle exponents in any way. So it's going to fail when it finds the + symbol in the string. Basically, Int64.Parse when using Unity does not support exponents.

Mono's Int32.Parse does seem to look for exponents, but still causes an OverflowException with all exponents that I give it.

Decimal.Parse actually does work with the same parameters as the other two, which suggests there was nothing wrong with the string or parameters, but it's just a bug in their other Parse methods. Decimal's parsing is completely different from how the Int parsing is being done, so that may explain why it works and the others don't.

Nic Foster
  • 2,864
  • 1
  • 27
  • 45