Artem Kyba - 1 month ago 8
C# Question

# Get string from large double value(C#)

Can't find simple way to convert double to string. I need to convert large numbers without distortion. Such as:

double d = 11111111111111111111;
string s = d.ToString();
Console.WriteLine(s);
//1.11111111111111E+19

How to get string value from double value exactly the same as user enter.

11111111111111111111111 => "11111111111111111111111"

1.111111111111111111111 => "1.111111111111111111111"

When using
ToString()
from
11111111111111111111
we get
"1.11111111111111E+19"
but not
"11111111111111111111"

double is a floating point type. So it has a limited accuracy. In your example, you could do something like this:

double d = 11111111111111111111;
string s = d.ToString("F0");
Console.WriteLine(s);

But as you'll see,this would output 11111111111111100000 instead of 11111111111111111111,so it has lost accuracy in the process. So the answer here is use the right type for the work. If you need a string, use a string variable to store the value.

Edit

This was the question i was trying to find that explains the problem with floating point math., thanks to @GSerg

Source (Stackoverflow)