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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Creating a Money class is the way to go. Using BigDecimal( or even an int) underneath. Then using Currency class to define rounding convention.
Unfortunately without operator overloading Java makes it quite unpleasant creating such basic types.
BigDecimal
or another fixed point representation is what is generally needed for money.Floating point (
Double
,Float
) representations and calculations are inexact, leading to erroneous results.There is a better library, timeandmoney. IMO, it far superior to the libraries provided by the JDK for representing these 2 concepts.
There are always constraints and specifics involved. Anyone without sufficient experience to appreciate the subtle issues outlined in the following article should seriously reconsider before dealing with real-world financial data:
http://lemnik.wordpress.com/2011/03/25/bigdecimal-and-your-money
BigDecimal is hardly the only correct representation or the only piece of the puzzle. Given certain conditions, using a Money class backed by cents stored as an integer could be sufficient and would be much faster than BigDecimal. Yes, that implies the use of dollars as currency and limits amounts but such constraints are perfectly acceptable for many use cases and all currencies have special cases for rounding and sub-denominations anyway, so there's no "universal" solution.
BigDecimal
all the way. I've heard of some folks creating their ownCash
orMoney
classes which encapsulate a cash value with the currency, but under the skin it's still aBigDecimal
, probably withBigDecimal.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.You can use the DecimalFormat class when ultimately displaying a currency value. It provides localization support and is pretty extensible.