Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a float with full precision in C++

In C++, can I write and read back a float (or double) in text format without losing 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 precision is lost sometimes. However, if I print the value with enough digits, I should be able to read back the exact same value.

Is there a given set of flags that is guaranteed to never lose precision? Would this behaviour be portable across platforms?

like image 631
luispedro Avatar asked Sep 06 '11 17:09

luispedro


People also ask

What is the precision of float in C?

float is a 32-bit IEEE 754 single precision Floating Point Number – 1 bit for the sign, 8 bits for the exponent, and 23* for the value. float has 7 decimal digits of precision.

How do you set a precision of a float?

To set the precision in a floating-point, simply provide the number of significant figures (say n) required to the setprecision() function as an argument. The function will format the original value to the same number of significant figures (n in this case).

How do you write a floating-point in C?

Floating-point constants are positive unless they're preceded by a minus sign ( - ). In this case, the minus sign is treated as a unary arithmetic negation operator. Floating-point constants have type float , double , or long double . The Microsoft C compiler internally represents long double the same as type double .


1 Answers

If you don't need to support platforms that lack C99 support (MSVC), your best bet is actually to use the %a format-specifier with printf, which always generates an exact (hexadecimal) representation of the number while using a bounded number of digits. If you use this method, then no rounding occurs during the conversion to a string or back, so the rounding mode has no effect on the result.

like image 159
Stephen Canon Avatar answered Sep 28 '22 07:09

Stephen Canon