C#将20位精度双精度转换为字符串并再次返回 [英] C# Converting 20 digit precision double to string and back again
问题描述
在C#中。我有一个双数字(我从数据库中提取),具有20位精度。在Visual Studio(使用QuickWatch)中,我可以看到double的值为= 0.00034101243963859839。
In C#. I have a double (which I've extracted from a database) that has 20 digit precision. In Visual Studio (using QuickWatch) I can see the value of the double to be = 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();
在这些情况下:
s = 0.000341012439638598
s2 = 0.00034101243963859800
s3 = 0.00034101243963859800
s4 = 0.0341012439638598
我想要能够做以下:
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??
推荐答案
使用R数字格式字符串:
double d = 0.00034101243963859839;
string s = d.ToString("R");
//...
double d2 = double.Parse(s);
if(d == d2)
{
//-- Success
}
R
代表往返。从链接的文档:
The R
stands for "round-trip". From the linked document:
此格式仅适用于单和双类型。往返说明符保证转换为字符串的数值将被解析为相同的数值。
This format is supported only for the Single and Double types. The round-trip specifier guarantees that a numeric value converted to a string will be parsed back into the same numeric value.
我怀疑没有办法保留最后两位数字。只有这么多精度可用,我怀疑他们首先将它们变成 d
。但是您可以确保您的字符串至少读取您所做的正确。
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. 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.
这篇关于C#将20位精度双精度转换为字符串并再次返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!