aameen951
Ameen Sayegh
52 posts

#5994
How to convert (format) double to string? 3 years, 5 months ago
for the last few days, I was trying to write a function that convert IEEE 754 double precision floating points to string and it turns out to be more difficult than I expected.
When the exponent is in the range (the decimal point is within the mantissa) it is not that difficult to format it to string but when the exponent it outside the range (there is many zeros to left or to the right) you need multiprecision representation of the number so you can do multiplication and division. I looked at glibc implementation of printf and it actually uses the MP library to handle this case. Does anyone know a complete implementation of float formatting that I can look at? I wonder what Casey will do when replacing snprintf? Here is the function that I have written:

cubercaleb
Caleb
12 posts
None 
#5995
How to convert (format) double to string? 3 years, 5 months ago Edited by Caleb on Feb. 28, 2016, 5:16 p.m.
I would look into Dragon4 for starters, after that I would read this:
http://www.cs.tufts.edu/~nr/cs257/archive/florianloitsch/printf.pdf Here is a link with the Dragon4 implementation: http://www.ryanjuckett.com/progra.../printingfloatingpointnumbers/ None 
mmozeiko
Mārtiņš Možeiko
1963 posts
/ 1 project

#6000
How to convert (format) double to string? 3 years, 5 months ago Edited by Mārtiņš Možeiko on Feb. 28, 2016, 8:21 p.m.
Yes, to accurately print all floating point numbers you will need to use multipleprecision integer implementation. If you can put some limitations (like only 2 fractional digits needed or similar) then you can probably get away with simpler method.
To test your function  loop over all valid floats. They are not so many, only ~4 billion:

aameen951
Ameen Sayegh
52 posts

#6001
How to convert (format) double to string? 3 years, 5 months ago Edited by Ameen Sayegh on March 1, 2016, 6:51 a.m.
@cubercaleb Thanks man the second link is just super amazing.
The explanation is soooo good. 