How does Double.toString() work if a fraction number cannot be precisely represented in binary?

前端 未结 2 1099
猫巷女王i
猫巷女王i 2021-01-13 09:28

I am unable to understand how Double.toString() works in Java/JVM. My understanding is that in general fraction numbers cannot be represented precisely in floating point typ

2条回答
  •  我在风中等你
    2021-01-13 10:00

    I am somewhat novice, so I hope someone with more experience can answer more thoroughly, but here is what I theorize is the reason...

    Formatting

    Although this is for the .NET framework and not specifically Java, I imagine that they work similarly: the toString method uses an optional formatter input, and most likely Java uses something similar, formatting the double to a close approximation in the toString method. Considering that Oracle specifically states that toString should be concise and easy-to-read, likely such a method is implemented for Double.toString().

    Only Necessary Digits to Distinguish...

    This is about as much documentation as I could find on the specifics of the Double.toString() method -- note the last paragraph:

    How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument d. Then d must be the double value nearest to x; or if two double values are equally close to x, then d must be one of them and the least significant bit of the significand of d must be 0.

    I am curious what it means by "adjacent values of type double" (other variables?), but it seems to also concur with the above -- toString and other methods likely only use as few digits as possible to uniquely identify the double, rounding when the number is arbitrarily close enough, as in the case of 23.675999999999 being "close enough" to 23.676. Or I could be wildly misunderstanding the documentation.

提交回复
热议问题