从大双值中获取字符串(C#)

Get string from large double value(C#)

找不到将双精度型转换为字符串的简单方法。我需要在不失真的情况下转换大数字。如:

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

如何从与用户输入完全相同的双精度值中获取字符串值。

11111111111111111111111 => "11111111111111111111111"

1.111111111111111111111 => "1.111111111111111111111"

知道怎么做吗?

double是浮点型。所以它的准确性有限。在您的示例中,您可以这样做:

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

但是正如您将看到的,这将输出 11111111111111100000 而不是 11111111111111111111,因此它在此过程中失去了准确性。所以这里的答案是为工作使用正确的类型。如果您需要字符串,请使用字符串变量来存储值。

编辑

This was the question 我试图找到解释浮点数学问题的方法。感谢@GSerg

首先:11111111111111111111111 对于双精度值和这个值来说太大了:1.111111111111111111111 因为双精度最大十进制长度是 17。

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

因此,您应该使用 BigInteger 然后 ToString 来格式化输出。
nuget 目录中还有一个名为 BigRational 的库,从未使用过,似乎处于 Beta 阶段,但可能有助于解决此问题。

一般情况下,你不能这样做:用户可以很好地输入,比如123,在很多方式:

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

等当您将用户输入转换为 double 时,您丢失了初始格式:

string userInput = ...

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

如果你想降低指数 如果可能你可以

double value = 11111111111111111111;

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

请注意,double64 位 来存储值,这就是为什么 大数字不可避免地会出现失真的原因:

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

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

可能你想要 BigInteger 而不是 double:

using System.Numerics;

...

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

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