Java fast money representation?

1.4k Views Asked by At

I'm working on a real time application that deals with money in different currencies and exchange rates using BigDecimal, however I'm facing some serious performance issues and I want to change the underlying representation.

I've read again and again that a good and fast way of representing money in Java is by storing cents (or whatever the required precision is) using a long. As one of the comments pointed out, there are some libs with wrappers that do just that, such as FastMoney from JavaMoney.

Two questions here.

  1. Is it always safe to store money as a long (or inside a wrapper) and keep everything else (like exchange rates) as doubles? In other words, won't I run into basically the same issues as having everything in doubles if I do Math.round(money * rate) (money being cents and rate being a double)?

  2. FastMoney and many other libs only support operations between them and primitive types. How am I supposed to get an accurate representation of let's say the return of an investment if I can't do profit.divide(investment) (both being FastMoney). I guess the idea is I convert both to doubles and then divide them, but that would be inaccurate right?

1

There are 1 best solutions below

5
On

The functionality you are looking for is already implemented in the JavaMoney Library.

It has a FastMoney class that does long arithmetic which is exactly what you have asked for.

For New Java Developers - Why long and not double?

Floating point arithmetic in Java leads to some unexpected errors in precision due to their implementation. Hence it is not recommended in financial calculations.

Also note that this is different from the precision loss in long arithmetic calculations which is due to the fractional portion not being stored in the long. This can be prevented during implementation by moving the fractional portion to another long (e.g. 1.05 -> 1 dollar and 5 cents).

References

  1. A Quick Tutorial

  2. Project Website