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?
Using Math.round() method is another method to limit the decimal places in Java. If we want to round a number to 1 decimal place, then we multiply and divide the input number by 10.0 in the round() method. Similarly, for 2 decimal places, we can use 100.0, for 3 decimal places, we can use 1000.0, and so on.
Float is a datatype which is used to represent the floating point numbers. It is a 32-bit IEEE 754 single precision floating point number ( 1-bit for the sign, 8-bit for exponent, 23*-bit for the value. It has 6 decimal digits of precision.
Long variables can hold numbers from -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807. Operations with Long are slightly slower than with Integer . If you need even larger values, you can use the Decimal Data Type.
The C++ setprecision can also be used to format only the decimal places instead of the whole floating-point or double value. This can be done using the fixed keyword before the setprecision() method.
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;
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