views:

283

answers:

4

How do I prevent my double value from being rounded when converting to a string? I have tried both Convert.ToString and ToString() with the same result.

For example my double may look something like 77.987654321, and the two strings conversions convert to to 77.98765. I need to keep the precision of the value as is.

+2  A: 

Jon Skeet's DoubleConverter class has a ToExactString() method which will return the exact value of the double as a string.

http://www.yoda.arachsys.com/csharp/DoubleConverter.cs

Robert Harvey
+4  A: 

Try something like

myDouble.ToString("R")

See also The Round-trip ("R") Format Specifier:

The round-trip ("R") format specifier guarantees that a numeric value that is converted to a string will be parsed back into the same numeric value.

Thomas
A: 

No guarantees, but try ToString("R").

Andrey Shchekin
+6  A: 

By default the .ToString() method of Double returns 15 digits of precision. If you want the full 17 digits that the double value holds internally, you need to pass the "G17" format specifier to the method.

String s = value.ToString("G17");

Sourced from the MSDN docs:

By default, the return value only contains 15 digits of precision although a maximum of 17 digits is maintained internally. If the value of this instance has greater than 15 digits, ToString returns PositiveInfinitySymbol or NegativeInfinitySymbol instead of the expected number. If you require more precision, specify format with the "G17" format specification, which always returns 17 digits of precision, or "R", which returns 15 digits if the number can be represented with that precision or 17 digits if the number can only be represented with maximum precision.

Simon P Stevens
It makes one wonder why they don't just return all 17 digits automatically, and let users round it if they want to.
Robert Harvey
@Robert: I know what you mean. It's strange that they miss them off. If it was hundreds I'd understand, but for the sake of 2 digits it seems odd.
Simon P Stevens
Note that it says "a *maximum* of 17 digits". The last two may probably be inaccurate, which seems like a valid reason to leave them out by default.
Thomas
@Robert: Because you hardly ever need them. 15 digits is enough to almost always recover the right number, and it also means that rounding often works to shorten the number correctly. Doing better than that is possible, but the code to do it is *much* more complex and few languages/libraries bother. (Tcl is one that does which is why I know a bit more about this than most folks...)
Donal Fellows