Search code examples
floating-pointprecisiontostringieee-754

How are binary floating points (IEEE 754) converted to decimal (i.e. to string)?


It's possibly a very stupid question, but I've been searching for a whole day and I couldn't get an answer...

Let's say I have a double-precision floating point literal: 5.21. Calling Double.toString( 5.21 ) in Java yields the string "5.21".

Now, let's say we have Java, but without toString and valueOf, nor can I format it with String.format or just by concatenation. How would I be able to convert my number to a string, assuming that I only have the binary representation?

More specifically, how do Double.toString and dtoa exactly work: how can I write my own toString/dtoa function (assuming we're dealing with IEEE 754 double-precision floating points)?


Solution

  • This is a surprisingly tricky problem, especially to do it efficiently and accurately. There are two main concerns:

    1. Each binary-float represents a set of "real" numbers centered around it, and the size of this interval depends on the value itself. (In general, the larger the value, the larger the interval it represents.) A "correct" conversion is usually defined as picking an element in this set, which will contain many decimal floats.

    2. Of the "correct" choices, one usually wants the "optimal" output, i.e., the string with the least number of decimal digits.

    So, as with anything floating point, the rabbit-hole goes deep even for innocuous-sounding questions like this. A good algorithm is both correct and optimal in the above sense; which makes it tricky to design one that is also efficient.

    But you're in luck. It's also a very well studied problem:

    It’s amazing that the first and the last paper above are 20 years apart, attesting to the difficulty of the problem. If you come up with a better technique, it’d definitely be a publishable result. Enjoy!