How do you format a float in C++ to output to two decimal places rounded up? I'm having no luck with setw
and setprecision
as my compiler just tells me they are not defined
.
cout << "Total : " << setw(2) << total << endl;
total outputs: Total : 12.3961
I'd like it to be: 12.40
or 12.39
if it's too much work to round up.
You need to include <iomanip>
and provide namespace scope to setw and setprecision
#include <iomanip> std::setw(2) std::setprecision(5)
try:
cout.precision(5); cout << "Total : " << setw(4) << floor(total*100)/100 << endl;
or
cout << "Total : " << setw(4) << ceil(total*10)/10 << endl;
iostream provides precision function, but to use setw, you may need to include extra header file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With