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)?
This is a surprisingly tricky problem, especially to do it efficiently and accurately. There are two main concerns:
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.
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:
Burger and Dyvbig's paper is the standard reference: https://www.cs.indiana.edu/~dyb/pubs/FP-Printing-PLDI96.pdf
A newer algorithm (faster but suboptimal) called Grisu is described here: https://drive.google.com/file/d/0BwvYOx00EwKmcTZUM0Q4VW1DTHc/view
And here's yet another paper along the same lines, the most recent as far as I know: https://ranjitjhala.github.io/static/fp-printing-popl16.pdf
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!