Artem Kyba Artem Kyba - 1 year ago 71
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();

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

11111111111111111111111 => "11111111111111111111111"

1.111111111111111111111 => "1.111111111111111111111"

When using
we get
but not

Answer Source

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

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.


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