在 C# 中。我有一个精度为 20 位的 double (我从数据库中提取的)。在 Visual Studio(使用 QuickWatch)中,我可以看到 double 值 = 0.00034101243963859839。
我想在文本框中显示此值,然后在将其取出并将其转换回 double 值时使其保持相同的值。但是我总是丢最后两位数
我试过以下方法:
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
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
}
有什么方法可以保持最后两位数的精度吗??
最佳答案
使用“R”numeric format string:
double d = 0.00034101243963859839;
string s = d.ToString("R");
//...
double d2 = double.Parse(s);
if(d == d2)
{
//-- Success
}
R
代表“往返”。来自链接文档:
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
中。但是您可以确保您的字符串至少能正确读回您所拥有的内容。
如果您确实需要额外的精度,您可以尝试使用 decimal
。
关于C# 将 20 位精度 double 转换为字符串并再次返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/611552/