Is JScience money unit conversion inverted?

110 Views Asked by At

I just came across this odd behaviour of JScience (4.3.1) when converting EUR to USD with the fictive conversion rate 1.05 (meaning I get 1.05 USD if I pay 1 EUR):

Currency unitMoney1 = Currency.EUR;
Currency unitMoney2 = Currency.USD;
Currency.setReferenceCurrency(unitMoney1);
unitMoney2.setExchangeRate(1.05);
result = unitMoney1.getConverterTo(unitMoney2).convert(1.0);
System.out.println(result);
    //prints 0.9523809523809523 (unexpected, should be 1.05)
result = unitMoney2.getConverterTo(unitMoney1).convert(result);
System.out.println(result);
    //prints 1.0 (expected)

Conversion from one length unit into another works differently:

Unit<Length> unitLength1 = (Unit<Length>) Unit.valueOf("m");
Unit<Length> unitLength2 = (Unit<Length>) Unit.valueOf("mm");
double result = unitLength1.getConverterTo(unitLength2).convert(1.0);
System.out.println(result);
// prints 1000.0

Maybe I just have a knot in my brain, but even in this minimal reproduction I don't seem to figure this out.

1

There are 1 best solutions below

0
On

The setExchangeRate() method "Sets the exchange rate of this Currency relatively to the reference currency." In your example, the reference currency should be Currency.USD, not Currency.EUR.

Currency.setReferenceCurrency(Currency.USD);
Currency.EUR.setExchangeRate(1.05); // 1.0 € = 1.05 $
System.out.println(Currency.EUR.getConverterTo(Currency.USD).convert(1.0));

This prints 1.05, as expected. See also setReferenceCurrency().