Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float formatting in C++

Tags:

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.

like image 235
eveo Avatar asked Jan 21 '13 03:01

eveo


1 Answers

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.

like image 185
billz Avatar answered Sep 28 '22 02:09

billz