3

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.

  • 1
    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. – apoteet Dec 04 '19 at 17:52
  • that's it. Thanks a lot! Don't know why we use all the time FastMoney ... going to change that. – kartoffelsack Dec 04 '19 at 18:11

1 Answers1

0

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.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140