C++ double precision and rounding off

2019-01-20 05:11发布

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?

4条回答
姐就是有狂的资本
2楼-- · 2019-01-20 05:38

I want to set precision of doubles 2 digits after point

Just multiply by 100 and use integers then.

查看更多
SAY GOODBYE
3楼-- · 2019-01-20 05:40

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

查看更多
叼着烟拽天下
4楼-- · 2019-01-20 05:45

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; }
查看更多
SAY GOODBYE
5楼-- · 2019-01-20 06:03

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.

查看更多
登录 后发表回答