开发者

Rounding to the second decimal spot [duplicate]

This question already has answers here: Round a float to a regular grid of predefined points (11 answers) Closed 5 years ago. 开发者_Python百科

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're expecting an exact result in a double or float, it may be impossible. Many numbers that can be exactly represented in two decimal digits can't be represented in the base 2 floating point numbers at all, and all you'll get is the nearest equivalent. For example you might find that 1.10 is stuck at 1.1000000000000001 no matter how many times you try to round it.


You didn't specify which kind of rounding you need. Assuming rounding to the nearest integer:

#include <math.h>
#include <stdio.h>

double round(double x) { return floor(x * 100 + 0.5) / 100; }

int main()
{
    printf("%g\n", round(12.345));
}

It prints 12.35.

Or if you just want to print a number rounded to two digits after decimal point:

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


Check out round() for float in C++ which talks about rounding floats although not to 2 places. The same basic techniques should work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜