Digit limitation from decimal point in C++

Are you actually trying to round the number, or just change its displayed precision?

For the former (truncating the extra digits):

double scale = 0.01;  // i.e. round to nearest one-hundreth
value = (int)(value / scale) * scale;

or (rounding up/down as appropriate, per jheriko’s answer)

double scale = 0.01;  // i.e. round to nearest one-hundreth
value = floor(value / scale + 0.5) * scale;

For the latter:

cout << setprecision(2) << value;

where the parameter to setprecision() is the maximum number of digits to show after the decimal point.

Leave a Comment