C#转换20位precision双串,然后再返回 [英] C# Converting 20 digit precision double to string and back again

查看:229
本文介绍了C#转换20位precision双串,然后再返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#。我有了20位precision双(我已经从数据库中提取)。在Visual Studio(使用快速监视)我可以看到双重的价值是= 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

我试过以下内容:

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
}

有没有什么办法让precision ??

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
}

研究表示往返。从链接的文档:

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.

顺便说一句,我怀疑有没有办法让那些最后两位数字。这里只有这么多precision可用,我怀疑他们曾经把它变成 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.

如果你确实需要额外的precision,你可以尝试使用小数代替。

If you really need the additional precision, you might try using a decimal instead.

这篇关于C#转换20位precision双串,然后再返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆