How to Output a Double Value with all the Decimal Places in Debugger or Console

霸气de小男生 提交于 2019-12-23 21:25:56

问题


I wish to extract double value completely when I am debugging an application, so that I can use it to construct a test case to feed into my geometry algorithm.

How to extract the double value out-- down to very last decimal places allowed by the double datatypes in C#-- and output it in either debugger windows, or using Console.WriteLine command?

Edit: My problem is that the algorithm that takes the double value as input will only fail if I insist of input the whole double value, right down to the very last digit. And since I want to reproduce it in a test case, that's why I would need such a full representation of the double value.


回答1:


I have a DoubleConverter class which does exactly what you want, by the sounds of it. Use it like this:

string text = DoubleConverter.ToExactString(doubleValue);

You need to make sure you understand that just because the output has a large number of digits, that doesn't mean it has that much precision. You may want to read my article on binary floating point in .NET for more information - or you may be aware of all of this to start with, of course.

Note that if you only want a string value which can be round-tripped, you don't need any extra code - just use the "r" format specifier:

string text = doubleValue.ToString("r");

I agree with Jackson Pope's general approach of using tolerance in equality comparisons for tests, but I do find it useful sometimes to see the exact value represented by a double. It can make it easier to understand why a particular calculation has come out one way or another.




回答2:


Instead of trying to output a binary number as a decimal number to a very large number of decimal places and do an exact comparison, instead do a comparison with an epsilon value that is your acceptable error and set epsilon to be very small. E.g.

 double epsilon = Math.Abs(actual - expected);
 Assert.That(epsilon, Is.LessThan(0.000000000001);


来源:https://stackoverflow.com/questions/4732680/how-to-output-a-double-value-with-all-the-decimal-places-in-debugger-or-console

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