RSS Feed Subscribe to RSS Feed


Representing Money in Java

I’ve been writing some code recently that required dealing with monetary values but, as hard as it is to believe, there still doesn’t seem to be a great solution for money in Java. I’ve known for a while that float and double should never be used for representing money, or indeed anywhere exact values are required (e.g. 1 – 0.9 may give you something like 0.09999999999999998). Using long or int gives exact answers but requires keeping track of the decimal point yourself, which is a pain. A common approach is to use BigDecimal, but that is not without its limitations either e.g. it is certainly clunkier to use than primitives, and slower, and the rules for rounding and presentation seem a little complex.

Another solution is to use timeandmoney. It is a little worrying that it is still pre-alpha (v0.5.1 at time of writing), but I am going to go with it in the absence of any better contenders.

Note that some of this is covered in Josh Bloch’s definitive book, Effective Java, that I posted about before, and there are some discussions about the issues here.

Tags: ,

One Response to “Representing Money in Java”

  1. admin |

    Update: I’ve been using timeandmoney some more, and it’s pre-alpha status is showing a little. There is very little documentation on the sourceforge site and the javadocs are a little wanting. For example, the main class that I am interested in, Money, has no class level javadocs, and the constructor’s java docs state
    “The constructor does not complex (sic) computations and requires simple, inputs consistent with the class invariant”.
    Not exactly enlightening.

    Also, there seem to be a few broken links on the site. When I try access the release notes from the main site at
    all I get is an error page:
    “An error has been encountered in accessing this page.”
    And the ‘About’ page at
    brings me to a ‘About Apache HTTP Server’ page. Annoying.

Leave a Reply