Reputation: 7440
Why does this simple Console App Output 100000000000000
instead of 99999999999999.99
or atleast 99999999999999.984
as the debugger is showing?
static void Main(string[] args)
{
double bigNum = 99999999999999.99;
Console.WriteLine(bigNum); //Console.WriteLine will internally ToString, but you can add what ever ToString() you want here the result will always be undesired
}
Console Output:
Debug Output:
For clarification:
Yes, I know of the value type decimal
and its superiour precision over double
, but I never heard of that ToString()
of double
could give wrong results.
Upvotes: 2
Views: 387
Reputation: 17648
See: MSDN for the standard ToString
conversion:
If format is null or an empty string, the return value is formatted with the general numeric format specifier ("G").
This will show you, that the defaulted number format specifier "G", will default to max 15 digits if possible: G-format specifier
As requested:
double bigNum = 99999999999999.99;
Console.WriteLine(bigNum); //default
//100000000000000
Console.WriteLine(bigNum.ToString("G")); //explicit default
//100000000000000
Console.WriteLine(bigNum.ToString("G17")); //G17
//99999999999999.984
Upvotes: 2