Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Is ToString() Rounding My Double Value?

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.

like image 684
user163757 Avatar asked Jan 20 '10 21:01

user163757


People also ask

How to display Double value in String c#?

ToString() Method is used to convert the numeric value of the current instance to its equivalent string representation.

What is the argument type of double ToString ()?

toString(double d) method returns a string representation of the double argument. The argument d is the double value to be converted.

How do I convert ToString?

ToString(Int32, IFormatProvider) Converts the value of the specified 32-bit signed integer to its equivalent string representation, using the specified culture-specific formatting information.


2 Answers

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.

like image 156
Simon P Stevens Avatar answered Sep 28 '22 00:09

Simon P Stevens


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.

like image 34
Thomas Avatar answered Sep 28 '22 02:09

Thomas