When saving a double to a string there is some loss of precision. Even if you use a very large number of digits the conversion may not be reversible, i.e. if you convert a double x
to a string sx
and then convert back you will get a number x'
which may not be bitwise equal to x
. This may cause some problem for instance when checking for differences in a battery of tests. One possibility is to use binary form (for instance the native Binary form, or HDF5) but I want to store the number in a text file, so I need a conversion to a string. I have a working solution but I ask if there is some standard for this or a better solution.
In C/C++ you could cast the double to some integer type like char*
and then convert each byte to an hexa of length 2 with printf("%02x",c[j])
. Then for instance PI would be converted to a string of length 16: 54442d18400921fb
. The problem with this is that if you read the hexa you don get any idea of which number it is. So I would be interested in some mix for instance pi -> 3.14{54442d18400921fb}
. The first part is a (probably low precision) decimal representation of the number (typically I would use a "%g"
output conversion) and the string in braces is the lossless hexadecimal representation.
EDIT: I pass the code as an aswer