简体   繁体   中英

string.format(format,doubleValue) , precision lost

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 ?

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM