I looked for a while and couldn’t find an answer on here, but it seems to be a kind of weird question. I’m working with the fstream library in C++. What I’m trying to do is take data from an input file, assign it variables, and output this to both the screen and the output file. This is all for a project i’m working on that calculates the monthly payment of the car loan, which is why the variables are named the way they are.
My data file looks like this:
105670.00 12345.00 0.057 4
and essentially what is happening is I am losing everything after the decimal of the first two numbers (regardless of what i put as the decimal), but it doesn’t happen to the 3rd number. additionally, when i try to setprecision(2) of the first two numbers i get a strange logic error, which i will show after my code.
my code looks like this:
#include<fstream>
#include<iomanip>
#include<iostream>
using namespace std;
int main ()
{
ifstream din; // These are my input and output files
ofstream dout;
float purchasePrice; // The first number of the input file.
float downPayment; // Second number.
float annualInterest; // Third number.
float numYears; // Last number.
// declaring the input/output files code here
din >> purchasePrice >> downPayment >> annualInterest >> numYears;
cout << purchasePrice << endl;
cout << downPayment << endl;
cout << annualInterest << endl;
cout << setprecision(2) << purchasePrice << endl;
cout << setprecision(2) << downPayment << endl;
cout << setprecison(2) << annualInterest << endl;
}
and here is my output:
105670
12345
0.057
1.1e+005
1.2e+004
0.057
I want my output to be:
105670.00
12345.00
0.057
105670.00
12345.00
0.05
Additionally, when performing any calculations, the numbers act as if they still have everything after the decimal. My question is, why are only some of the floats truncating, and why does setprecision() not work the way it is expected in this case?
Any responses are greatly appreciated, I’m sorry its such a lengthy explanation.
You also need to set the
fmtflagstofixed:Without specifying
scientificorfixed, the output mechanisms will use whatever scheme is deemed to be best. You know what’s “best”, and that’s a fixed point scheme. For more detail, see http://en.cppreference.com/w/cpp/io/manip .Even better is not to use floating point numbers at all when dealing with money. It is far better to use some fixed point arithmetic package.