Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to model an amount of Money in Java [closed]

Can anybody recommend a class library or a design pattern that models amounts of Money?

I guess it should support:

  • multiple currencies
  • a mechanism to indicate the number of decimals
  • math (respecting certain rounding conventions (cfr ie. Banker's Rounding))
  • serialisation to and from a String representation
  • ... ?

I.e. 19.99 USD could be serialized into "USD-2-00000001999"
(Whereas 2 indicates the number of decimals)

like image 369
Jan Avatar asked Nov 10 '10 14:11

Jan


People also ask

How do you represent money in Java?

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.

What is the datatype for working with money in Java?

1 Answer. Java has Currency class that represents the ISO 4217 currency codes. BigDecimal is the best type for representing currency decimal values.

What data type should be used for money?

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

What data type you use for cash related projects?

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.


1 Answers

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

like image 76
Pascal Thivent Avatar answered Oct 18 '22 12:10

Pascal Thivent