Write a float with full precision in C ++

In C ++, can I write and read a float (or double) in text format without loss of precision?

Consider the following:

float f = ...; { std::ofstream fout("file.txt"); // Set some flags on fout fout << f; } float f_read; { std::ifstream fin("file.txt"); fin >> f; } if (f != f_read) { std::cout << "precision lost" << std::endl; } 

I understand why accuracy is sometimes lost. However, if I print a value with enough digits, I should be able to read the same value.

Is there a certain set of flags guaranteed never to lose accuracy? Will this behavior be portable across platforms?

+4
source share
4 answers

If you do not need to support platforms that do not support C99 (MSVC), the best choice is to use the %a format specifier with printf , which always generates an exact (hexadecimal) representation of the number when using a limited number of digits. If you use this method, then when converting to a string or vice versa, rounding does not occur, therefore, the rounding mode does not affect the result.

+4
source

if I print a value with enough digits, I should be able to read the exact value

No, if you write it in decimal, there is no integer relationship between the number of binary digits and the number of decimal digits needed to represent a number. If you print your number in binary or hexadecimal, you can read it without losing any accuracy.

In general, floating point numbers are not primarily portable between platforms, so your textual representation will not be able to bridge this gap. In practice, most machines use IEEE 754 floating point numbers, so they are likely to work quite well.

+4
source

Take a look at this article: How to print floating point numbers correctly , and also in the following: Print floating point numbers quickly and accurately .

Stackoverflow is also mentioned here , and there is some pointer to implementation here .

+3
source

You cannot print the exact value of "power of two" float in decimal format.
Consider using base 3 to store 1/3, now try and print 1/3 in excellent decimal.

For solutions, see How do you print the EXACT value of a floating-point number?

+1
source

All Articles