javacurrencyarithmeticexceptionjava-money

java MonetaryConversions throws ArithmeticException for high digit currencies


I'd like to use standard java MonetaryConversions to convert currencies.

At first glance it works very well and simple:

    @Test
    public void testConversion()
    {
        FastMoney usd = FastMoney.of(1000, Monetary.getCurrency("USD"));
        usd.with(MonetaryConversions.getConversion("EUR"));
    }

However I find that is throws ArithmeticExceptions, when I use currencies that have high nominal values like japanese yen or Mexican Pesos

    @Test
    public void testArithmeticException()
    {
        FastMoney jpy = FastMoney.of(1000, Monetary.getCurrency("JPY"));
        jpy.with(MonetaryConversions.getConversion("EUR"));
    }

throws following exception

java.lang.ArithmeticException: 0.0082769 can not be represented by this class, scale > 5

    at org.javamoney.moneta.FastMoney.getInternalNumber(FastMoney.java:197)
    at org.javamoney.moneta.FastMoney.multiply(FastMoney.java:388)
    at org.javamoney.moneta.FastMoney.multiply(FastMoney.java:84)
    at org.javamoney.moneta.spi.AbstractCurrencyConversion.apply(AbstractCurrencyConversion.java:118)
    at org.javamoney.moneta.FastMoney.with(FastMoney.java:594)
    at tech....GatewayTransactionConverterTest.testArithmeticException(GatewayTransactionConverterTest.java:207)

Checking the code of FastMoney I see that the exception is quite hardcoded and I cant find anything where I could reduce e.g. the scale.

But with this the conversion offered by java out of the box is quite useless as I cannot convert for really a lot of currencies. I cannot imagine that nobody has this issue. But I can't find anything with google.


Solution

  • As dementis mentions in a comment:

    Can you use the bigdecimal-based Money class?The FastMoney class is based on longs, which you shouldn't rely on for high precision currency calculations.

    this worked for me.