BigDecimal和金钱 [英] BigDecimal and Money

查看:146
本文介绍了BigDecimal和金钱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我研究发现,在处理货币时,进行计算的最佳方法是使用BigDecimal类.

I've researched and found that when dealing with currency, the best way to go about doing calculations is by the BigDecimal class.

考虑到这一点,我正在编写一个将各种类型的外币转换为美元,反之亦然的代码(特别是将外币转换成美元,计算找零和收益的收银机)这笔钱以外币形式支付给客户).

With that in mind, I'm working on a code that converts various types of foreign currency into US currency and vice-versa (specifically, a cashregister that takes foreign currency and converts it into US money, computes the change and returns this amount to the customer in foreign currency).

到目前为止,许多方法都使用double,其中两种方法将int作为参数来计算美元.

As of now, many of the methods use double and two of them take in int as a parameter to be used in computing the US currency.

问题:

由于我想在计算中使用BigDecimal类,我是否应该将所有进行双精度计算的方法都更改为BigDecimal?

Since I want to use the BigDecimal class in my calculations, should I change all my methods that make calculations involving doubles to a BigDecimal?

推荐答案

是的,您应该更改所有浮点数或双精度数以采用整数,长整型或BigDecimals.

Yes, you should change all floats or doubles to take either ints, longs or BigDecimals.

浮点数和双精度数对于财务计算而言并不精确.使用 Money 模式处理金额和货币(这是一个很好的主意) Quantity 的特殊类型).为了维护可能以多种货币表示的货币清单,您实际上在做的是MoneyBagMoney的集合,然后可以将给定目标货币和CurrencyExchangeService的所有值求和(货币转换率也应被存储为BigDecimals).

Floats and doubles are not precise for financial calculations. It's a very good idea to use the Money pattern to deal with amounts and currencies (it's a special type of Quantity). To maintain a list of moneys possibly in multiple currencies, what you're effectively doing is a MoneyBag, a collection of Money that can then sum all values given a target currency and a CurrencyExchangeService (currency conversion rates should also be stored as BigDecimals).

在每次操作后都应根据所需的小数位数和舍入算法进行舍入.小数位数通常是Currency的属性(例如,参见 ISO 4217 );除非需要一个不同的数字(例如,在对汽油进行定价时).

Rounding should be done after every operation according to the number of desired decimal places and the rounding algorithm. The number of decimal places is normally a property of the Currency (look, e.g., at ISO 4217); unless a different number is desired (like when pricing gasoline, for example).

您绝对应该看看福勒的例子;但我还创建了一个非常简单的单一货币锻炼 Money 类>.它仅使用美元,并四舍五入到小数点后两位.但这仍然是将来扩展的良好基础.

You should definitely look at Fowler's examples; but I've also created a very simple uni-currency Money class for an exercise. It uses dollars only and rounds to 2 decimal places; but it's still a good base for future extensions.

这篇关于BigDecimal和金钱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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