1

I have the following problem:

double a = 6.005; double b = 5.995;

I want to set precision of doubles 2 digits after point, for example

double c = a+b;// I would like to get 11.99 not 12.00.

How can I do this?

iammilind
  • 68,093
  • 33
  • 169
  • 336
  • Please do explain what `a*b` should be. `double` is of course a floating-point type, and your point doesn't float. – MSalters Jul 29 '11 at 15:12
  • Could the OP please edit the question, now that it is clear, that `a = 6.005 -> 6.00` and the like is wanted? – Dilettant Jul 29 '11 at 15:12

4 Answers4

12

Precision is one thing; rounded for display is quite another.

I think this is wrong headed. You should want all the precision you can get and worry about rounding for display when the results are complete.

UPDATE:

You should not be representing currency using doubles. Last time I looked, C++ was an object-oriented language. You should create an abstraction for Money that does the right thing and abstracts these details away from clients of the class.

You can create a Money class that manages a private representation of the currency as cents if you're working in dollars. Do all your calculations using integers and render at the end.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • +1 I totally agree... rounding should be that last step in the calculation – Pepe Jul 29 '11 at 15:03
  • 1
    Suppose that this doubles mean dollars and cents! Then I can not have 11 dollars and 995 cents. So i want to know is there any ready function in C++ that do it for me 11.995==>11.99 –  Jul 29 '11 at 15:03
  • IIRC, banks typically do their math in microdollars. Yes, that's 6 extra digits, not 2. – MSalters Jul 29 '11 at 15:15
10

I want to set precision of doubles 2 digits after point

Just multiply by 100 and use integers then.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
4

You should probably use fixed point numbers:

unsigned int a = 600;
unsigned int b = 599;

unsigned int c = a + b;

unsigned int make_fixed(double d) { return d * 100; }

void print_fixed(unsigned int n) { std::cout << n/100 << "." << n%100; }
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
1

No, you either need to adjust all values one by one (mul by 100, take int part, div by 100), or you need to write your own MySpecialDouble class (that does the same just behind the scene).

imre
  • 1,667
  • 1
  • 14
  • 28