Representing Monetary Values in Java [closed]

2019-01-01 12:29发布

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?

14条回答
琉璃瓶的回忆
2楼-- · 2019-01-01 12:52

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.

查看更多
梦醉为红颜
3楼-- · 2019-01-01 12:54

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.

查看更多
时光乱了年华
4楼-- · 2019-01-01 12:58

There is a better library, timeandmoney. IMO, it far superior to the libraries provided by the JDK for representing these 2 concepts.

查看更多
深知你不懂我心
5楼-- · 2019-01-01 12:59

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.

查看更多
长期被迫恋爱
6楼-- · 2019-01-01 13:00

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.

查看更多
看风景的人
7楼-- · 2019-01-01 13:03

You can use the DecimalFormat class when ultimately displaying a currency value. It provides localization support and is pretty extensible.

查看更多
登录 后发表回答