Handling money and currencies in Java with JSR 354

Back in May 2015, JSR 354 featuring an API for handling monetary values and currencies was finally released. The specification consists of the following things:

  • An API for handling e. g. monetary amounts and currencies
  • SPIs to support interchangeable implementations
  • Factories for creating instances of the implementation classes
  • Functionality for calculations, conversion and formatting of monetary amounts

The JSR 354 project is hosted at javamoney.org where you can also find the reference implementation.

How does the API work

When using the JSR API, you can create MonetaryAmount instances using a MonetaryAmountFactory. An example of creating a MonetaryAmount and printing it to the console looks like this:

MonetaryAmountFactory<?> amountFactory = Monetary.getDefaultAmountFactory();
MonetaryAmount monetaryAmount = amountFactory.setCurrency(Monetary.getCurrency("EUR")).setNumber(12345.67).create();
MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(Locale.getDefault());
System.out.println(format.format(monetaryAmount));

When using the reference implementation API, the necessary code is much simpler:

MonetaryAmount monetaryAmount = Money.of(12345.67, "EUR");
MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(Locale.getDefault());
System.out.println(format.format(monetaryAmount));

The API also supports calculations with MonetaryAmounts:

MonetaryAmount monetaryAmount = Money.of(12345.67, "EUR");
MonetaryAmount otherMonetaryAmount = monetaryAmount.divide(2).add(Money.of(5, "EUR"));

There’s much more possible with JSR 354 which is far beyond the scope of this post…

Using JSR 354 right now

It’s currently not clear whether JSR 354 will be part of Java 9 or Java EE 8. But the good news is, you can start using it right now.

The JSR 354 API is available in the Maven Central repository and can be consumed using the following dependency:

<dependency>
  <groupId>javax.money</groupId>
  <artifactId>money-api</artifactId>
  <version>1.0</version>
</dependency>

The reference implementation is also available in the Maven Central repository

<dependency>
  <groupId>org.javamoney</groupId>
  <artifactId>moneta</artifactId>
  <version>1.0</version>
</dependency>

Be aware that the JSR 354 API is only compatible with Java 8+ but there are backported versions of the JSR 354 API and reference implementation available for Java 7.

Short URL for this post: http://wp.me/p4nxik-2wo
This entry was posted in Java Basics, Java EE and tagged , . Bookmark the permalink.

One Response to Handling money and currencies in Java with JSR 354

  1. Finally Java has a standard way to work with money =)

Leave a Reply