Formatting Floating Point Numbers
The implementation described here works with IEEE 754 double precision floating-point format which has the following bit layout (source)
Let’s look at the π constant as an example:
This is not easy to parse, so let’s split the number into sign, exponent, and fraction, store them in a struct and create a simple formatter for pretty printing:
Now we can do
Here is a sign, is a biased (offset by 1023) exponent, is a fraction, and is the actual exponent. Because for 53-bit significand (52 bit fraction + implicit 1), 17 decimal digits should be enough for the round trip, i.e. reading the number back will give the same binary representation. This is great but if we make use of the extra bits we should normalize the number, i.e. shift the significand left until the top-most bit is one and adjust the exponent to compensate for that:
To get powers of 10 for scaling, we can store a table of precomputed powers in the normalized form and look them up based on the binary exponent.
Source: www.zverovich.net