tags:

views:

1149

answers:

7

Hello,

I'm new in C++.I have double variable double a=0.1239857 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 implement digit limitation of floating-point variable? Or How can i change precision of a variable?

Best regards...

+1  A: 

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
David Cournapeau
+4  A: 

This will result in two digits after the decimal place.

a = floor(a * 100.0) / 100.0;
bradtgmurray
+5  A: 

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.

Alnitak
Note that when you use setprecision on a stream like you show, it will round also.
Brian Neal
Brian - please elaborate. Sure, it'll _show_ the value rounded up or down to the appropriate number of places, but it won't change the value actually stored in the variable.
Alnitak
The value will be rounded to the appropriate precision upon display to cout. Of course it has no effect on the value in the variable.
Brian Neal
I was trying to say it does both: setprecision shows the value to the desired precision, *and* rounds while doing so.
Brian Neal
A: 

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.

schnaader
+1  A: 

Use a ios_base::precision for formatting i/o.

dirkgently
+1  A: 

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

Brian Neal
A: 

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.

jheriko