C# Converting 20 digit precision double to string and back again
Asked Answered
G

2

32

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();

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??

Gipon answered 4/3, 2009 at 17:9 Comment(0)
B
62

Use the "R" numeric format string:

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.

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.

Benzoic answered 4/3, 2009 at 17:12 Comment(2)
"As an aside, I suspect there is no way to keep those last two digits." - But how can Visual Studio "see" those two digits?Susceptible
Just a FYI, but when drilling down into the linked article, it says "For Double and Single values, the "R" format specifier in some cases fails to successfully round-trip the original value and also offers relatively poor performance. Instead, we recommend that you use the "G17" format specifier for Double values and the "G9" format specifier to successfully round-trip Single values."Vapory
K
1

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). decimal has a maximum of 28/29 digits (96 bit), so it would be ok to use it. If you have higher precisions in the database, you need an own bignum class for C#, look in stackoverflow for implementations.

Kendalkendall answered 7/12, 2009 at 23:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.