Artem Kyba
Artem Kyba

Reputation: 885

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"

Any ideas how it can be done?

Upvotes: 6

Views: 1353

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186718

In general case, you can't do this: user can well input, say 123, in many a way:

  • 123
  • 123.00
  • 1.23e2
  • 12.3E1
  • 123.0e+00
  • 1230e-1

etc. When you convert the user input into double you loose the initial format:

string userInput = ...

// double is just 123.0 whatever input has been
double value = double.Parse(userInput);

In case you want to drop exponent if it's possible you can

double value = 11111111111111111111;

string result = value.ToString("#######################");

And, please, notice, that double has 64 bit to store the value, that's why a distortion is inevitable for large numbers:

// possible double, which will be rounded up
double big = 123456789123456789123456789.0;

// 1.2345678912345679E+26
Console.WriteLine(big.ToString("R"));
// 123456789123457000000000000
Console.WriteLine(big.ToString("###########################")); 

May be you want BigInteger instead of double:

using System.Numerics;

...

BigInteger value = BigInteger.Parse("111111111111111111111111111111111"); 

// 111111111111111111111111111111111
Console.WriteLine(value.ToString());

Upvotes: 1

Tinwor
Tinwor

Reputation: 7973

First of all: 11111111111111111111111 is to large for a double value and also this value: 1.111111111111111111111 since the double max decimal length is 17.

By default, a Double value contains 15 decimal digits of precision, although a maximum of 17 digits is maintained internally.

For this reason you should use BigInteger and then ToString for formatting the output.
There is also a library in the nuget Directory called BigRational, never used and seems in Beta stage but probably will help in solving this problem.

Upvotes: 2

Pikoh
Pikoh

Reputation: 7703

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

Upvotes: 8

Related Questions