Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing double values

Tags:

c#

On my system, the following code prints '3.6':

double a = 1.2;
int b = 3;

double c = a * b;

Console.WriteLine(c);

But in the debugger, I can see that c has a value with more than 2 digits:

enter image description here

I know that I can display the full representation with Console.WriteLine("{0:R}", c). Is this the only and recommended way to display the actual value of a double?


update

Going with the above example, I'd like to print c such that if the user were to take the printed value and insert that back into the code in a test using ==, the comparison would be true. In this case c == 3.5999999999999996 returns true.

like image 443
dharmatech Avatar asked Dec 29 '12 00:12

dharmatech


1 Answers

Console.WriteLine calls Double.ToString which uses the the "G" format specifier. This uses the current culture to determine the number of decimal places (1 for "en-US").

If you want to display 8 decimal places you can use the numeric format specifier:

Console.WriteLine(c.ToString("N8"));

Standard Numeric Format Strings

Edit: The debugger uses this method to convert a double to a string:

_ecvt_s

I assume it's the cheapest way to convert it.

Where i have found it: How does Visual Studio display a System.Double during debugging?

like image 146
Tim Schmelter Avatar answered Oct 08 '22 08:10

Tim Schmelter