8

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?

averageUsername123
  • 725
  • 2
  • 10
  • 22
  • 1
    There's no need to do the rounding yourself unless you need it rounded for your own purposes. Whatever you use to set the number of digits should do rounding on the output. – Mark Ransom Jan 30 '13 at 03:41
  • I wrote on this subject recently. [Check it out!][1] [1]: http://stackoverflow.com/questions/13090868/converting-floats-and-integers-to-char/13092103#13092103 – Olof Forshell Feb 03 '13 at 20:58

3 Answers3

20

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;
billz
  • 44,644
  • 9
  • 83
  • 100
11

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);
gerrytan
  • 40,313
  • 9
  • 84
  • 99
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;
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180