If I have a double
variable, I want to store its value in a file to two decimal places with the standard rules of rounding off. I don't just want to store and display data up to two decimal places but I also want to do arithmetic using this data, when I reopen the file, exactly up to two decimal places. In other words when I read this data from the file into a double
variable, I want this data to be accurately loaded to two decimal places also, exaclty as I stored it. Using <iomanip>
and fixed
and setprecision
from what I have seen so far are only used for displaying the output to be used with std::cout
. I may be wrong though. Please explain using the following example how to accomplish this? Also how to store data from a double
variable up to two decimal places in a binary
file also?
std::ofstream file("data.txt");
int hours = 8, mins= 35;
char ap='p';
double format_24_hr=0.00;
format_24_hr = static_cast<double>(hours) + 12.00 + static_cast<double>(mins)/60.00;
file<<format_24_hr; // how to store double to two decimal places in a binary file
file.close();
Also, when I'm reading the file like follows, how do I make sure that it's loading the data to two decimal places exactly as I stored it?
std::ifstream file("data.txt");
double var=0.00;
file>>var; // would the data read here be exactly loaded to two decimal places as I stored it?
file.close();