C++ double precision and rounding off

允我心安 提交于 2019-11-28 13:01:28

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.

I want to set precision of doubles 2 digits after point

Just multiply by 100 and use integers then.

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; }

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!