简体   繁体   中英

Weird behaviour of Double.ToString()

I am trying to convert the double value 9007199254740992.0 to a string.

But there seems to be a rounding error (the last 2 becomes a 0):

(9007199254740992.0).ToString("#")    // Returns "9007199254740990"
(9007199254740992.0).ToString()       // Returns"9.00719925474099E+15"

First I thought that maybe the number couldn't be represented as a double. But it can. This can be seen by casting it to a long and then converting it to a string.

((long)9007199254740991.0).ToString() // Returns "9007199254740991"
((long)9007199254740992.0).ToString() // Returns "9007199254740992"

Also, I found that if I use the "R" format , it works.

(9007199254740992.0).ToString("R")    // Returns "9007199254740992"

Can anyone explain why ToString("#") doesn't return the double with the integer part at full precision?

As can be seen on MSDN :

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.

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