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

后端 未结 3 392
没有蜡笔的小新
没有蜡笔的小新 2021-01-15 05:20

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.

Ass         


        
相关标签:
3条回答
  • 2021-01-15 06:00

    You could convert both to a string : actualValue.ToString("0.000") and compare those strings.

    That could be made to match your requirements closely.

    0 讨论(0)
  • 2021-01-15 06:02

    If you want to test whether the default display values match, just compare the default display values:

    Assert.AreEqual(expectedValue.ToString(), actualValue.ToString());
    
    0 讨论(0)
  • 2021-01-15 06:06

    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").

    0 讨论(0)
提交回复
热议问题