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 be 0.12. I know C++ have functions that return largest or smallest integer that is greater or lower than a like ceil or floor.
Is there a function that implements digit limitation of floating-point variable? Or How can I change precision of the a variable?
9 Answers
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.
This will result in two digits after the decimal place.
a = floor(a * 100.0) / 100.0; 1If 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.
What do you mean by you want to limit the variable ? The value or its formatting. For the value, you can use floor + division. Something like:
double a = 0.12123 double b; b = floor(a * 100) / 100 Use a ios_base::precision for formatting i/o.
You can set the precision on a stream, e.g.
double d = 3.14579; cout.precision(2); cout << d << endl; // Or use a manipulator #include <iomanip> cout << setprecision(2) << d << endl; Note that when you send a double or float to a stream like this, it will automatically round for you (which can trip you up sometimes if you aren't aware of this).
0An 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.
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; You can write your own function as follows, it can handle rounding errors for decimals as well.
double RoundForGivenPrecision(const double dNumber, int iDecimalPlaces) { long long multiplier = (long long)pow(10, iDecimalPlaces); long double value = dNumber < 0 ? (long long)((nextafter(dNumber, -DBL_MAX)*multiplier)-0.5) : (long long)((nextafter(dNumber,DBL_MAX)*multiplier)+0.5); return value / multiplier; }