Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lossless conversion of float to string and back: is it possible?

This question refers to the IEEE standard floating point numbers used on C/x86.

Is it possible to represent any numeric (i.e. excluding special values such as NaN) float or double as a decimal string such that converting that string back to a float/double will always yield exactly the original number?

If not, what algorithm tells me whether a given number will suffer a conversion error?

If so, consider this: some decimal fractions, when converted to binary, will not be numerically the same as the original decimal value, but the reverse is not true (because the binary has bounded precision so any decimal expansion is finite and perfect if not truncated), so here's another question...

Is it ever necessary to introduce deliberate errors into the decimal representation in order to trick the atof (or other) function into yielding the exact original number, or will a naive, non-truncating toString function be adequate (assuming exact conversion is possible in general)?

like image 843
spraff Avatar asked Jan 24 '12 16:01

spraff


People also ask

Can you convert a float to a string?

We can convert float to a string easily using str() function.

Can a float be converted to a double?

The doubleValue() method of Java Float class returns a double value corresponding to this Float Object by widening the primitive values or in simple words by directly converting it to double via doubleValue() method .

Can we convert our variable from string to float?

You can use the float() function to convert any data type into a floating-point number. This method only accepts one parameter. If you do not pass any argument, then the method returns 0.0. If the input string contains an argument outside the range of floating-point value, OverflowError will be generated.

Can you convert float to string C++?

We can convert float and double to string using the C++11 std::to_string() function. For the older C++ compilers, we can use std::stringstream objects.


1 Answers

According to this page:

Actually, the IEEE754-1985 standard says that 17 decimal digits is enough in all cases. However, it seems that the standard is a little vague on whether conforming implementations must guarantee lossless conversion when 17 digits are used.

So storing a double as a decimal string with at least 17 digits (correctly rounded) will guarantee that it can be converted back to binary double without any data loss.

In other words, if every single possible double-precision value were to be converted to a decimal string of 17 digits (correctly rounded), they will all map to different values. Thus there is no data-loss.


I'm not sure on the minimum cut-off for single-precision though. But I'd suspect that it will be 8 or 9 digits.

like image 178
Mysticial Avatar answered Sep 25 '22 06:09

Mysticial