tags:

views:

84

answers:

4

Hi

I was wondering if there is any way in c++ to treat a double with a given precision. for example, the number 3.1345 will be considered as 3.13 and the number 0.009 will be considered as 0 (precision of 2 after the dot).

I need that it will be applied on mathematical operations. for example:

double a = 0.009;
double b = 3.12345

//a should be considered as 0, b as 3.12

double c = a*b // should output 0.
double d = a+b // should output 3.12

since the function setprecision() is for std i was wondering if there is any other function to do that.

thanks

+6  A: 

That's not going to work correctly with doubles, ever. Doubles are binary fractions, they don't have decimals or decimal precision. Read The Floating-Point Guide for details.

If you need specific decimal behaviour, you'll have to drop doubles and use a decimal data type. You may find double-based solutions that appear to work, but you'll always hit cases where it won't.

Michael Borgwardt
FWIW, internal representation is a completely different topic than formatted output. A number may have 100 decimal resolution, but can be printed with only 2. Most programmers like to have better internal resolution.
Thomas Matthews
A: 

double a = 3.12345; double b = ((int) a*100) / 100.0;

UnixShadow
And if "((int) a*100) / 100.0" can't be represented perfectly as a double? It won't always work.
colithium
But I was in the middle of typing this up as the "closest" solution given he sticks with doubles. You should mention the flaw though.
colithium
And then, b != 3.12
Michael Borgwardt
A: 

The easiest way:

int a100 = int(a*100);
int b100 = int(b*100);
int c100 = a100 * b100; // Will be 0
int d100 = a100 + b100; // Will be 312
MSalters
Of course, this can be improved by defining a `decimal<N>` template with appropriate `iostream` overloads.
MSalters
A: 

have a look at floor() and ceil()

http://www.cplusplus.com/reference/clibrary/cmath/floor/

a=floor(a); b=floor(b*100)/100;

Jaydee