Does insertion and extraction of a floating point number to some of the standard stream classes preserves its value?
c++, floating-point
Solution
Not necessarily. By default, `ostream` outputs 6 digits of precision. To be able to "round trip" a float, you need a precision of `std::numeric_limits<float>::max_digits10` (which is 9 for the most common representation). If the stream is being used for persistance, and you're only persisting floats, just set the precision before writing anything, e.g.:
ss.precision( std::numeric_limits<float>::max_digits10 );
(If you need to handle both `float` and `double`, and don't want the extra digits on `float`, you'll need to set the precision each time you output a floating point value.)
Problem
When I debug I sometimes want to print the floating point number returned by a function and use it as an input value for another function. I wonder what are the default parameters which guide the formatting of the floating point numbers. Are f1 and f2 always the same in the following code? ``` #include <sstream> #include <cassert> int main(int argc, const char *argv[]) { std::stringstream ss; float f1 = .1f; ss << f1; float f2; ss >> f2; assert(f1 == f2); return 0; } ``` Can I write a bunch of floating point numbers to std::cout or std::ofsteam and read them back to get exactly the same numbers or should I explicitly set the amount of numbers after the decimal mark (like it is suggested here? What bothers me is that although .1 is not representable as a binary fraction it is still formatted correctly by the standard streams.