C++双精度和四舍五入
我有以下问题:
double a = 6.005; double b = 5.995;
我想设置点后双精度 2 位数字,例如
double c = a+b;// 我想得到 11.99 而不是 12.00
。
我该怎么做?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能应该使用定点数字:
You should probably use fixed point numbers:
不,您要么需要一一调整所有值(mul 乘 100,取 int 部分,div 乘 100),或者需要编写自己的 MySpecialDouble 类(在幕后执行相同的操作)。
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).
精度是一回事,但又是一回事。圆形显示则完全是另一回事。
我认为这是错误的。您应该希望获得尽可能多的精度,并担心结果完成后显示的舍入问题。
更新:
您不应该使用双精度数来表示货币。上次我看的时候,C++ 是一种面向对象的语言。您应该为 Money 创建一个抽象,它可以做正确的事情,并将这些细节从类的客户端中抽象出来。
如果您使用的是美元,则可以创建一个 Money 类来管理以美分为单位的货币的私有表示形式。使用整数进行所有计算并在最后渲染。
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.
只需乘以 100 并使用整数即可。
Just multiply by 100 and use integers then.