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

前端 未结 2 1567
说谎
说谎 2020-12-03 06:59

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

相关标签:
2条回答
  • 2020-12-03 07:17

    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.

    0 讨论(0)
  • 2020-12-03 07:36

    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.

    0 讨论(0)
提交回复
热议问题