C# .Net double issue… 6.8 != 6.8?

依然范特西╮ 提交于 2019-12-01 08:15:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!