Question

I have this double value:

var value = 52.30298270000003

and when I convert it to string, it losses its precision:

var str = string.Format("{0} some text...", value);
Console.WriteLine(str); // output: 52.3029827

The number of precision on my double value may be changed at run-time. How can I force the string.Format method to use all precision?

Was it helpful?

Solution

You want to use the R format specifier

From the MSDN

Result: A string that can round-trip to an identical number.

Supported by: Single, Double, and BigInteger.

Precision specifier: Ignored.

More information: The Round-trip ("R") Format Specifier.

String.Format("{0:R} some text...", value)

will give you

52.30298270000003 some text...

OTHER TIPS

Try this:

var value = 52.30298270000003;

var str = string.Format("{0} some text...", value.ToString("R"));
Console.WriteLine(str); // output: 52.3029827

The MSDN documnetation has the following to say about the ToString method of Singles and Doubles and using ToString("R"):

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top