Representing Monetary Values in Java
Solution 1
BigDecimal
all the way. I've heard of some folks creating their own Cash
or Money
classes which encapsulate a cash value with the currency, but under the skin it's still a BigDecimal
, probably with BigDecimal.ROUND_HALF_EVEN
rounding.
Edit: As Don mentions in his answer, there are open sourced projects like timeandmoney, and whilst I applaud them for trying to prevent developers from having to reinvent the wheel, I just don't have enough confidence in a pre-alpha library to use it in a production environment. Besides, if you dig around under the hood, you'll see they use BigDecimal
too.
Solution 2
It can be useful to people arriving here by search engines to know about JodaMoney: http://www.joda.org/joda-money/.
Solution 3
I'm not expressing my opinion here, but there are quite good arguments against BigDecimal that someone should probably throw out:
http://lemnik.wordpress.com/2011/03/25/bigdecimal-and-your-money/
Solution 4
A convenient library that I ran into earlier is the Joda-Money library. One of its implementations is indeed based on BigDecimal. It is based on the ISO-4217 specification for currencies and can support a customized currency list (loaded via CVS).
This library has a small number of files that one can quickly go through if modifications are needed. Joda-Money is published under the Apache 2.0 license.
Solution 5
If you are just using dollars and cents, I'd use a long (offset by 2 decimal places). If you need more detail, big decimal may be the way to go.
Either way, I'd probably extend the class to have a .toString() that uses the correct format, and as a place to put other methods that might come up (For a long, multiplying and dividing will go awry if the decimal isn't adjusted)
Also, if you use define your own class and interface, then you can replace the implementation at will.
aylnon
Global Head of Developer Relations at PayPal. Open Source leader. Founder and former-CTO of NodeSource. Ex-CEO of The Node Firm. Always bet on Node.js ✨
Updated on September 09, 2020Comments
-
aylnon over 3 years
I understand that BigDecimal is recommended best practice for representing monetary values in Java. What do you use? Is there a better library that you prefer to use instead?