问题
I was doing some unit testing at work and a peculiar error popped up for one of the assertions. Note that expectedValue and actualValue are both doubles.
Assert.AreEqual(expectedValue, actualValue);
The exception stated that they were not equal, elaborating that "expected value: <6.8> actual value: <6.8>."
The expected value is a hard coded 6.8 and the actual value is formulated using database values going through our classification methods (such as Equal Records, or Jenks Natural Breaks).
My guess is that the difference is probably that the mantissas of the 2 values are similar up until the least significant bit. I updated the tests to include an epsilon to find if the two values are close enough, but I'm curious to if there is a way to force the mantissa to match with the display value of if I displayed that double. Does such a mantissa correction exist?
回答1:
I'm not entirely sure what you mean by forcing the mantissa to match the display value... there are no double values which are exactly 0.1, for example.
If you want some code to display the exact value of a double, however, I have a DoubleConverter.cs file which makes it easy:
double d = 0.1;
string x = DoubleConverter.ToExactString(d);
Another alternative is to use the round-trip format specifier ("r") when converting a double to string - that guarantees that the result has enough information to reproduce the same exact value later. In other words, if x != y
, then x.ToString("r") != y.ToString("r")
.
回答2:
You could convert both to a string : actualValue.ToString("0.000")
and compare those strings.
That could be made to match your requirements closely.
回答3:
If you want to test whether the default display values match, just compare the default display values:
Assert.AreEqual(expectedValue.ToString(), actualValue.ToString());
来源:https://stackoverflow.com/questions/3495237/c-sharp-net-double-issue-6-8-6-8