1

How to I get double.ToString to not sometimes truncate last digits.

If I show a double in Visualstudio Immediate window or Quickwatch I see 17 decimals. When I convert it to a string I see 15.
There is probably a good reason for this but my problem is how to get around it.

? 0.87912328514094507
0.87912328514094507
? 0.87912328514094507.ToString()
"0,879123285140945"

Dotnet 4.6.2 on a Win7 fwiw.

LosManos
  • 7,195
  • 6
  • 56
  • 107
  • 2
    `0.87912328514094507.ToString("R")` - *round trip* formatting - https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings – Dmitry Bychenko Nov 16 '18 at 06:54
  • 1
    Note that technically, both representations are truncating the underlying double. If your goal is to get an exact representation, you may want to consider using Jon Skeet's `DoubleConverter` class. See https://stackoverflow.com/a/1658420/18192 for discussion. Note that usually using the exact representation is inappropriate, since it displays more precision than a double can actually represent. – Brian Nov 16 '18 at 14:15

1 Answers1

11

There are two standard mechanisms for achieving that.

If you pass "R" as the argument to ToString then you get the round trip string. That is, the string where converting the double to a string, then the string back to a double always gives you the double you started with.

If you pass "G17" as the argument then you get the standard string format but extended to 17 decimal places.

You can certainly be forgiven for not knowing that! This mechanism is not particularly discoverable. I'm not a big fan of how formatting strings have failed to evolve in the last 40 years.

For more details, read the documentation: https://learn.microsoft.com/en-us/dotnet/api/system.double.tostring

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • 1
    It seems `"R"` does not always work for `double`. In [docs](https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#RFormatString) I read "For Double values, the "R" format specifier in some cases fails to successfully round-trip the original value. For both Double and Single values, it 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." – LosManos Nov 16 '18 at 07:30
  • Future readers: According to my comment @ericlippert 's comment was incorrect. As I understand `ToString("G17")` should be the correct answer. Should I remove the tick marking this answer as correct? – LosManos Nov 16 '18 at 12:18