Sriram
Sriram

Reputation: 10558

Writing numbers to a file with more precision - C++

I wrote some parameters (all of type double) to a file for use in performing some complex computations. I write the parameters to the files like so:

refStatsOut << "SomeParam:" << value_of_type_double << endl;
where refStatsOut is an ofstreamparameter. There are four such parameters, each of type double. What I see as written to the file is different from what its actual value is (in terms of loss of precision). As an example, if value_of_type_double had a value -28.07270379934792, then what I see as written in the file is -28.0727.

Also, once these stats have been computed and written I run different programs that use these statistics. The files are read and the values are initially stored as std::strings and then converted to double via atof functions. This results in the values that I have shown above and ruins the computations further down.

My question is this:
1. Is there a way to increase the resolution with which one can write values (of type double and the like) to a file so as to NOT lose any precision?
2. Could this also be a problem of std::string to double conversion with atof? If so, what other function could I use to solve this?

P.S: Please let me know in case some of the details in this question are not clear. I will try to update them and provide more details.

Upvotes: 0

Views: 5101

Answers (3)

Leon
Leon

Reputation: 1141

ofstream your_file;

you can use your_file.precision(X);

The main difference between precision() and setPrecision() is that precision returns the current precision and setPrecision doesn't. Therefore, you can use precision like this.

streamsize old_precision = your_file.precision(X);
// do what ever you want

//restore precision
your_file.precision(old_precision);

Upvotes: 3

Olipro
Olipro

Reputation: 3529

a double is basically a 64-bit integer, if you want a cheap way of writing it out, you can do something like this (note I'm assuming that your compiler uses long for 64-bit ints)

double value = 32985.932235;
long *saveme = (long*)&value;

Just beware of the caveat that the saved value may not remain the same if loaded back on a different architecture.

Upvotes: 1

Alok Save
Alok Save

Reputation: 206546

You can use the setprecision function.

Upvotes: 4

Related Questions