Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Representing Monetary Values in Java [closed]

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?

like image 231
dshaw Avatar asked Nov 12 '08 22:11

dshaw


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.

Which data type in Java should be used to represent monetary values?

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

Why should you not use float for money?

When doing any kind of calculation with currency, accuracy is extremely important. And floating point numbers (floats and doubles) don't have an accurate enough representation to prevent rounding errors from accumulating when doing arithmetic with monetary values.

What data type should you use for currency?

The best datatype to use for currency in C# is decimal. The decimal type is a 128-bit data type suitable for financial and monetary calculations. The decimal type can represent values ranging from 1.0 * 10^-28 to approximately 7.9 * 10^28 with 28-29 significant digits.


2 Answers

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.

like image 156
ninesided Avatar answered Sep 18 '22 17:09

ninesided


It can be useful to people arriving here by search engines to know about JodaMoney: http://www.joda.org/joda-money/.

like image 34
Iñaki Ibarrola Atxa Avatar answered Sep 17 '22 17:09

Iñaki Ibarrola Atxa