.NET has inconsistent behavior for parsing infinity and negative infinity depending on culture.
If you are using the CultureInfo.InvariantCulture
, the strings to use are "Infinity"
and "-Infinity"
.
var infinity = double.Parse("Infinity", CultureInfo.InvariantCulture);
var negativeInfinity = double.Parse("-Infinity", CultureInfo.InvariantCulture);
However, if you are in a specific culture, the strings to use are "∞"
and "-∞"
.
var infinity = double.Parse("∞", new CultureInfo("en-US"));
var negativeInfinity = double.Parse("-∞", new CultureInfo("en-US"));
Unfortunately, it doesn't seem that there are strings that will parse to infinity and negative infinity that work in every culture by default, including CultureInfo.InvariantCulture
. If you try to parse "∞"
or "-∞"
using CultureInfo.InvariantCulture
, it will throw a FormatException
.
Workaround
If you don't mind adding an additional helper method, you could make this work in any culture by changing the NumberFormatInfo.PostiveInfinitySymbol
and NumberFormatInfo.NegativeInfinitySymbol
to make every culture parse the strings you want.
public static IFormatProvider NormalizeInfinity(
string positiveInfinitySymbol = "Infinity",
string negativeInfinitySymbol = "-Infinity")
{
return NormalizeInfinity(CultureInfo.CurrentCulture, positiveInfinitySymbol, negativeInfinitySymbol);
}
public static IFormatProvider NormalizeInfinity(
IFormatProvider provider,
string positiveInfinitySymbol = "Infinity",
string negativeInfinitySymbol = "-Infinity")
{
NumberFormatInfo numberFormat;
if (provider is null)
{
numberFormat = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
}
else
{
numberFormat = (NumberFormatInfo)((NumberFormatInfo)provider.GetFormat(typeof(NumberFormatInfo))).Clone();
}
numberFormat.PositiveInfinitySymbol = positiveInfinitySymbol;
numberFormat.NegativeInfinitySymbol = negativeInfinitySymbol;
return numberFormat;
}
Usage
double infinity = double.Parse("Infinity", NormalizeInfinity());
double negativeInfinity = double.Parse("-Infinity", NormalizeInfinity());
double aDouble = double.Parse("1.23456", NormalizeInfinity());
double notANumber = double.Parse("NaN", NormalizeInfinity());
Note the above will work with the same symbols for infinity and negative infinity regardless if you set the CultureInfo.CurrentCulture
to CultureInfo.InvariantCulture
or not.
You can also pass through any culture and it will change the infinity and negative infinity settings, but leave all of the others intact.
double infinity = double.Parse("Infinity", NormalizeInfinity(new CultureInfo("de")));