Search code examples
c#stringfloating-pointieee-754

Not able to convert string value to float in C# according to IEEE 754


Well I have a string value of "1.36383E+37" and I want convert in float type according to IEEE 754. See the code below:

        try
        {
            return float.Parse(val, NumberStyles.Float | NumberStyles.AllowThousands, cultureInfo);
        }
        catch (Exception ex)
        {
        }

It is not able to parse the value and throwing me an exception of "Value was either too large or too small for a Single"

Any help would be thankful.


Solution

  • I suspect you are using a cultureInfo for a culture that uses . as a thousands separator. For example, CultureInfo.GetCultureInfo("it") (Italian) results with the error you describe for that data, as do several others. You should use a culture that matches the way the number is written. For machine-produced strings, CultureInfo.InvariantCulture would be the best option.