Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding to the second decimal spot [duplicate]

Tags:

c++

rounding

how do i round to the second decimal point in C++. thanks for your help.

like image 432
mike Avatar asked Oct 27 '10 05:10

mike


2 Answers

You can multiply by 100 and then round to an integer. Then put the decimal point after the first 2 digits.

For example:

void round(double x)
{
   double y = 100 * x;
   int rounded = (int)(y + 0.5);
   printf("%lf rounded = %d.%02d\n", x, rounded / 100, rounded % 100);
}
like image 118
Himadri Choudhury Avatar answered Sep 24 '22 20:09

Himadri Choudhury


When printing doubles you can specify the precision:

f,F

The double argument is rounded and converted to decimal notation in the style [-]ddd.ddd, where the number of digits after the decimal-point character is equal to the precision specification. If the precision is missing, it is taken as 6; if the precision is explicitly zero, no decimal-point character appears. If a decimal point appears, at least one digit appears before it.

Try:

printf("%f rounded = %.2f\n", x, x);

The same thing in C++

std::cout << x << " rounded = " << std::setprecision(2) << x << "\n";
like image 25
Martin York Avatar answered Sep 22 '22 20:09

Martin York