简体   繁体   English

C# 将 20 位精度 double 转换为字符串并再次返回

[英]C# Converting 20 digit precision double to string and back again

In C#.在 C# 中。 I have a double (which I've extracted from a database) that has 20 digit precision.我有一个具有 20 位精度的双精度数(我从数据库中提取的)。 In Visual Studio (using QuickWatch) I can see the value of the double to be = 0.00034101243963859839.在 Visual Studio(使用 QuickWatch)中,我可以看到双精度值 = 0.00034101243963859839。

I want to display this value in a textbox and then have it be the same value when I take it out and convert it back into a double.我想在文本框中显示这个值,然后当我把它拿出来并将它转换回双精度值时让它成为相同的值。 But I always lose the last two digits但我总是输掉最后两位数字

I've tried the following:我尝试了以下方法:

double d = 0.00034101243963859839;
string s = d.ToString();
string s2 = d.ToString("F20");
string s3 = d.ToString("0.00000000000000000000"); -- 20 0's
string s4 = (d*100d).ToString();

In these cases:在这些情况下:

s  = 0.000341012439638598
s2 = 0.00034101243963859800
s3 = 0.00034101243963859800
s4 = 0.0341012439638598

I want to be able to do the following:我希望能够做到以下几点:

double d = 0.00034101243963859839;
string s = d.ToString();
//...
double d2 = double.Parse(s);
if(d == d2)
{
  //-- Success
}

Is there any way to keep those last two digits of precision??有没有办法保持最后两位精度?

Use the "R" numeric format string :使用“R”数字格式字符串

double d = 0.00034101243963859839;
string s = d.ToString("R");
//...
double d2 = double.Parse(s);
if(d == d2)
{
  //-- Success
}

The R stands for "round-trip". R代表“往返”。 From the linked document:从链接的文档:

This format is supported only for the Single and Double types.仅 Single 和 Double 类型支持此格式。 The round-trip specifier guarantees that a numeric value converted to a string will be parsed back into the same numeric value.往返说明符保证转换为字符串的数值将被解析回相同的数值。

As an aside, I suspect there is no way to keep those last two digits.顺便说一句,我怀疑没有办法保留最后两位数。 There's only so much precision available, and I doubt they ever make it into d in the first place.可用的精度只有这么多,我怀疑他们是否会一开始就将其变为d But you can make sure your string at least reads back what you do have correctly.但是您可以确保您的字符串至少可以正确读取您所拥有的内容。

If you really need the additional precision, you might try using a decimal instead.如果您真的需要额外的精度,您可以尝试使用decimal

No. Besides the fact that double is binary and therefore not good for decimal values, doubles have a maximum of 15/16 decimal digits (53 bits).不可以。除了 double 是二进制的因此不适合十进制值这一事实之外,double 最多有 15/16 个十进制数字(53 位)。 decimal has a maximum of 28/29 digits (96 bit), so it would be ok to use it.十进制最多有 28/29 位(96 位),所以可以使用它。 If you have higher precisions in the database, you need an own bignum class for C#, look in stackoverflow for implementations.如果您在数据库中有更高的精度,您需要一个自己的 bignum class 用于 C#,查看 stackoverflow 的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM