how do i round to the second decimal point in C++. thanks for your help.
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);
}
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With