Rounding to 2 decimal points [duplicate]

2020-01-28 09:32发布

问题:

I've used the following to round my values to 2 decimal points:

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

and this seems to work fine; except for values like "16.60", which is "16.6".

I want to output this value like "16.60".

The way I'm outputting values is the following:

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

I've tried the following:

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

But that gave me answers like

1.2e+02

How can I output the values correctly?

回答1:

This is because std::setprecision doesn't set the digits after the decimal point but the significant 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 put std::fixed into your output stream:

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


回答2:

you can use printf / sprintf or other similar functions. Following code will format floating point value into two digits after decimals. Refer to the printf manual for more formatting info

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


回答3:

From Trevor Boyd Smith's comment:

If you are allergic to printf and friends there is the type safe C++ version in #include <boost/format.hpp> which you can use to do:

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