Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Digit limitation from decimal point in C++

Tags:

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?

like image 880
yalcin Avatar asked Apr 28 '09 13:04

yalcin


People also ask

How do you limit the numbers after a decimal point?

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.

How many decimal places can float hold in C?

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.

How many decimal places can long hold?

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.

How do I limit the number of decimal places in C++?

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.


2 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.

like image 62
Alnitak Avatar answered Oct 02 '22 12:10

Alnitak


This will result in two digits after the decimal place.

a = floor(a * 100.0) / 100.0; 
like image 39
bradtgmurray Avatar answered Oct 02 '22 12:10

bradtgmurray