Round to 2 decimal places

I used the following to round my values ​​to two decimal places:

 x = floor(num*100+0.5)/100;

and it seems to be working fine; except for values ​​such as "16.60", which is "16.6".

I want to display this value as "16.60".

The way to output the values ​​is as follows:

cout setw(12) << round(payment);

I tried the following:

cout setw(12) << setprecision(2) << round(payment);

But it gave me answers like

1.2e+02

How to display values ​​correctly?

+5
source share
3 answers

, std::setprecision , , , . , std:: fixed :

double a = 16.6;
std::cout << std::fixed << std::setprecision(2) << a << std::endl;
+18

printf/sprintf . . . . ​​

float f = 1.234567
printf("%.2f\n", f);
+10

From a comment by Trevor Boyd Smith:

If you are allergic to printf and friends, there is a safe version of C ++ type c #include <boost/format.hpp>that you can use:

float f = 1.234567;
cout << boost::format("%.2f") % f << endl;
+3
source

All Articles