Can anybody recommend a class library or a design pattern that models amounts of Money?
I guess it should support:
I.e. 19.99 USD could be serialized into "USD-2-00000001999"
(Whereas 2 indicates the number of decimals)
Representing money: use BigDecimal , int , or long ( BigDecimal is the recommended default) the int and long forms represent pennies (or the equivalent, of course) BigDecimal is a little more inconvenient to use, but has built-in rounding modes.
1 Answer. Java has Currency class that represents the ISO 4217 currency codes. BigDecimal is the best type for representing currency decimal values.
The MONEY data type stores currency amounts. TLike the DECIMAL(p,s) data type, MONEY can store fixed-point numbers up to a maximum of 32 significant digits, where p is the total number of significant digits (the precision) and s is the number of digits to the right of the decimal point (the scale).
That's the reason we should always prefer BigDecimal or BigInteger for financial calculations. Primitive type - int and long are also useful for monetary calculations if decimal precision is not required.
I would check the monetary module from the JScience project (by Jean Marie Dautelle).
Depending on your exact needs, Stephen Colebourne started Joda-Money ("a more focussed project" [than JScience]) some time ago. But there is no full release available yet (version 0.5 was released one year ago).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With