about write a float to file

If a write a float 0.776 to my file with binary mode,and then a i read it into a float variable,it become 0.77600002;
1
2
3
4
5
6
7
8
9
10
11
12
...
        float f = 0.776f;
	os.write((const char *)&f,sizeof(float));
	os.close();

	std::ifstream is("f:/test.bin",std::ios::binary);
	b = is.good();
	float f_ = 0.0f;
	is.precision(precision);
	is.read((char *)&f_,sizeof(float));
	is.close();
...


So,how can i hold the original value that i wrote previosly!Thanks~~~
Is the precision fixed? If so, you can save it as an int which is intfinitely precise:
[code]int intfl = f*pow(10.0,DIGITS);[code]
In this case, you'd set DIGITS to 3. You'd end up with the value 776 instead of 0.776, which can easily be transformed back to your original value.

If the precision/number of digits isn't fixed, it becomes more difficult. Of course, you could ask yourself if the 2*10^-8 makes a difference...
Looks like you just want to write and store a float to file (binary representation) and then read it back again? No need to call precision(). Just ran this little test and worked fine:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>

int main()
{
  float f1 = -187.33667, f2 = 0.0;
  std::ofstream out("test.bin",std::ios_base::binary);
  if(out.good())
  {
    std::cout << "Writing floating point number: " << std::fixed << f1 << std::endl;
    out.write((char *)&f1,sizeof(float));
    out.close();
  }
  std::ifstream in("test.bin",std::ios_base::binary);
  if(in.good())
  {
    in.read((char *)&f2,sizeof(float));
    std::cout << "Reading floating point number: " << std::fixed << f2 << std::endl;
  }
  return 0;
}
Last edited on
The "original value" that you wrote previously was 0.77600002.

Floats have a fixed set of valid values. The decimal number 0.776 is not a valid float. It lies between two valid floats: 0.77600002288818359375 (13019120 * 2-24) and 0.775999963283538818359375 (13019119 * 2-24). When you attempt to store 0.776 in a variable of type float, the compiler actually writes the nearest valid float value, which is 0.77600002288818359375 in this case.
Last edited on
Topic archived. No new replies allowed.