-1

I have simply question. How can this test fail? In comments are values of variables

[Fact]
public void ToNullableDouble_CorrectInput_ReturnsCorrectValue()
{
    double expectedValue = double.MaxValue; //1.7976931348623157E+308
    string expectedValueString = expectedValue.ToString(); //"1,79769313486232E+308" - fail, I do not know why
    string expectedValueString2 = expectedValue.ToString(CultureInfo.InvariantCulture); //"1.79769313486232E+308" - fail
    string expectedValueString3 = 1.75.ToString(); //"1,75" - pass
    string expectedValueString4 = 1.75.ToString(CultureInfo.InvariantCulture); //"1.75" - fail because of the culture

    double number;
    double? convertedValue = double.TryParse(expectedValueString, out number) ? number : (double?)null;
    //convertedValue = null, number = 0

    Assert.True(convertedValue.HasValue);
}

Float behaves pretty same, decimal is ok. I know what is the difference between decimally types. But I do not understand how can be MaxValue constant unconverted. It is not should be culture settings:

double.TryParse(expectedValueString, out number) ? number : (double?)null;
null
double.TryParse(expectedValueString2, out number) ? number : (double?)null;
null
double.TryParse(expectedValueString3, out number) ? number : (double?)null;
1.75
double.TryParse(expectedValueString4, out number) ? number : (double?)null;
null

For other values works correctly e.g.: 1.75

Marv
  • 441
  • 2
  • 14

1 Answers1

2

The problem is likely due to the fact that double.MaxValue was converted to a string. The string output doesn't contain all digits, instead it is rounded. Parsing this value overflows the double.

Solution 1:

string stringDouble = double.MaxValue.ToString("r");
double doubleValue = double.Parse(stringDouble); // No exception

The Round-trip ("R") Format Specifier

Solution 2:

string stringDouble = double.MaxValue.ToString();
double doubleValue;
if (!double.TryParse(stringDouble, out doubleValue)) 
{
    doubleValue = stringDouble.Equals(double.MaxValue) ? double.MaxValue : double.MinValue;
}
Odrai
  • 2,163
  • 2
  • 31
  • 62