Search code examples
c#.netparsingfloating-pointfloating-point-conversion

How do I parse floats and doubles case-insensitively in c# (to cover "infinity", etc.)?


In my locale, double.Parse("Infinity") returns double.PositiveInfinity, but double.Parse("infinity") throws System.FormatException. Analogous things happen for negative infinity and NaN.

I could obviously just use CultureInfo.CurrentCulture.NumberFormat.PositiveInfinitySymbol.Equals() with a case-insensitive comparison to check for a match before calling double.Parse() (and do likewise for negative infinity and NaN). However, I was hoping for something more elegant.


Solution

  • I don't see much option beyond doing a TryParse(), and, on failure, special-casing the three special tokens as is shown in Number.ParseDouble() and double.TryParse(). I'd do the check after rather than before since, in most cases, this won't happen.