When I try and round digits using setprecision(2) in C++, numbers like “0.093” re returned- THREE, not two digits after the decimal! I cannot figure out why this is. I’ve included my very rudimentary code below, in case I am severely missing some point. Thanks!
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double tax = 0.06 ; //Tax Rate
float cost ; //Cost of item
float computed ; //Non-rounded tax
cout << "Enter the cost of the item: " ;
cin >> cost ;
computed = tax*cost;
cout << "Computed: $" << computed << endl;
cout << "Charged: $" << setprecision(2) << computed << endl; //Computed tax rounded to 2 decimal places
return 0;
}
This is because
std::setprecisiondoesn’t set the digits after the decimal point but the significant (aka “meaningful”) digits if you don’t change the floating point format to use a fixed number of digits after the decimal point. To change the format, you have to putstd::fixed(documentaion) into your output stream: