Get string from big double value (C #)

Unable to find a simple way to convert double to string. I need to convert large numbers without distortion. For instance:

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

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

11111111111111111111111 => "11111111111111111111111"

1.111111111111111111111 => "1.111111111111111111111"

Any ideas how to do this?

+6
source share
3 answers

double - floating point type. Thus, it has limited accuracy. In your example, you can do something like this:

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

But, as you will see, this will lead to the conclusion 11111111111111100000 instead of 11111111111111111111 , so it lost accuracy in this process. So, the answer here uses the correct type to work with . If you need a string, use a string variable to save the value.

Edit

This was a question I was trying to find that explains the problem with floating point math thanks to @GSerg

+7
source

First of all: 11111111111111111111111 is great for a double value, and also this value: 1.111111111111111111111 , since the double maximum decimal length is 17.

By default, a double value contains 15 decimal digits of precision, although a maximum of 17 digits is supported domestically.

For this reason, you should use BigInteger and then ToString to format the output.
There is also a library in the nuget directory called BigRational , never used or shown in the Beta phase, but is likely to help solve this problem.

+2
source

In general, you cannot do this: the user can enter, say 123 , in many ways:

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

etc .. When you convert user input to double , you lose the original format:

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

If you want to reset the exponent, if possible, you can

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

And please note that double has 64 bits to store the value, so 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("###########################")); 

Maybe you want BigInteger instead of double :

 using System.Numerics; ... BigInteger value = BigInteger.Parse("111111111111111111111111111111111"); // 111111111111111111111111111111111 Console.WriteLine(value.ToString()); 
0
source

Source: https://habr.com/ru/post/1011938/


All Articles