I\'m new to C++. I have a double variable double a=0.1239857
and I want to limit variable a
from decimal point two digits. So a
will b
If you just want to output the value, you can do something like
printf("%.3f", a); // Output value with 3 digits after comma
If you want to convert the value itself, you can do:
a = (int)(a * 1000) / 1000.0f;
Note that both do no rounding, they just truncate the value.
you could also do something like this:
//This code will ask the user for an input, set the decimal precision to the hundredths place, and add 4.63 to the inputted variable
int banana;
cin >> banana;
cout << setprecision(2) << fixed << banana + 4.63;
Use a ios_base::precision for formatting i/o.
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.
An actual rounding solution would be x = floor(100*x + 0.5) / 100;
assuming the value to be rounded is in a variable "x".
The x = floor(100*x) / 100;
recommended by others here will actually truncate the number to 2dp instead.
This will result in two digits after the decimal place.
a = floor(a * 100.0) / 100.0;