Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding to 2 decimal points [duplicate]

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?

like image 716
averageUsername123 Avatar asked Jan 30 '13 03:01

averageUsername123


1 Answers

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;
like image 187
billz Avatar answered Sep 20 '22 15:09

billz