在C ++中存储货币值的最佳方式 [英] Best way to store currency values in C++

查看:135
本文介绍了在C ++中存储货币值的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道一个float不适合存储货币值,因为舍入错误。有没有标准的方式来表示钱在C + +?

I know that a float isn't appropriate to store currency values because of rounding errors. Is there a standard way to represent money in C++?

我看过boost库,没有发现任何东西。在java中,看起来BigInteger是一种方式,但我在C ++中找不到一个等价物。

I've looked in the boost library and found nothing about it. In java, it seems that BigInteger is the way but I couldn't find an equivalent in C++. I could write my own money class, but prefer not to do so if there is something tested.

推荐答案

不要存储它,我可以写自己的钱类,但不喜欢这样做。只是作为分,因为你会积累错误乘税和兴趣很快。至少,另外两个有效数字:$ 12.45将存储为124,500。如果你保持一个有符号的32位整数,你将有$ 200,000(正或负)。如果你需要更大的数字或更高的精度,一个有符号的64位整数可能会给你所有的空间,你需要很长一段时间。

Don't store it just as cents, since you'll accumulate errors when multiplying for taxes and interest pretty quickly. At the very least, keep an extra two significant digits: $12.45 would be stored as 124,500. If you keep it in a signed 32 bit integer, you'll have $200,000 to work with (positive or negative). If you need bigger numbers or more precision, a signed 64 bit integer will likely give you all the space you'll need for a long time.

它可能是一些帮助将这个值包装在一个类中,给你一个地方创建这些值,对它们进行算术,并将它们格式化以显示。这也将给你一个中心的地方,来携带存储的货币(美元,加元,欧元等)。

It might be of some help to wrap this value in a class, to give you one place for creating these values, doing arithmetic on them, and formatting them for display. This would also give you a central place to carry around which currency it being stored (USD, CAD, EURO, etc).

这篇关于在C ++中存储货币值的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆