I'm working on a project where I need to do some math and give the user output with dollars in it, so I would like to have my console tell the user an answer like $20.15
instead of $20.153
. I used the set precision function as such:
cout << setprecision(2);
, but rather than have the numbers become what I want them to be, they are converted into scientific notation.
I'm outputting a lot of numbers, so having a function like setprecision
would be best for me for ease of use.
How do I properly have the numbers displayed with only two decimal places and not have the console give me numbers in scientific notation?
Thanks
Nathan
EDIT:
Here is the part of my code I'm having problems with:
int main() {
cout << setprecision(2);
if (totalCostHybrid < totalCostNonHybrid) {
cout << "Hybrid car: " << endl;
cout << "Total cost: " << totalCostHybrid << endl;
cout << "Total gallons used: " << milesPerYear / hybridEffic << endl;
cout << "Total gas cost: " << gasCostHybrid << endl;
cout << "Non-hybrid car: " << endl;
cout << "Total cost: " << totalCostNonHybrid << endl;
cout << "Total gallons used: " << milesPerYear / nonHybridEffic << endl;
cout << "Total gas cost: " << gasCostNonHybrid << endl;
cout << "Hybrid is cheaper!" << endl;
}
Obviously there's more to it, but this is what I need help with.
To fix that, you should use fixed floating-point notation for cout. You can find more info here.
Try addind
cout << fixed
to your code, like the code below. To set the precision to2
, you can use theprecision
property.Here is the complete code:
Iostreams are a pain for formatting floating-point values. But why are you using floating-point to represent currency values? You should store integer pennies (or tenth-pennies) because, though you're not measuring in whole numbers of dollars, your values are actually fixed-point. And you really don't need the trouble that floating-point brings. And then you can stream the whole and "fractional" parts of your value separately (use
/
and%
!), as integers, with a'.'
in the middle.In the meantime, try
std::fixed
.Cheat and watch purists go crazy...