/** * Converts this amount to an equivalent amount the specified currency. * <p> * The result will be expressed in terms of the given currency, converting * using the specified FX rate. * <p> * For example, if this represents 'GBP 100' and this method is called with * arguments {@code (USD, 1.6)} then the result will be 'USD 160'. * * @param resultCurrency the currency of the result * @param fxRate the FX rate from this currency to the result currency * @return the converted instance, which should be expressed in the specified currency * @throws IllegalArgumentException if the FX is not 1 when no conversion is required */ public Money convertedTo(Currency resultCurrency, BigDecimal fxRate) { if (currency.equals(resultCurrency)) { if (DoubleMath.fuzzyEquals(fxRate.doubleValue(), 1d, 1e-8)) { return this; } throw new IllegalArgumentException("FX rate must be 1 when no conversion required"); } return Money.of(resultCurrency, amount.multiply(fxRate)); }
/** * Converts the current instance of {@link CurrencyAmount} to the equivalent {@link Money} instance. * This will result into loss of precision in the amount, since {@link Money} is storing the amount * rounded to the currency specification. * * @return The newly created instance of {@link Money}. */ public Money toMoney() { return Money.of(this.getCurrency(), this.getAmount()); }
/** * Converts this amount to an equivalent amount in the specified currency. * <p> * The result will be expressed in terms of the given currency. * If conversion is needed, the provider will be used to supply the FX rate. * * @param resultCurrency the currency of the result * @param rateProvider the provider of FX rates * @return the converted instance, in the specified currency * @throws RuntimeException if no FX rate could be found */ @Override public Money convertedTo(Currency resultCurrency, FxRateProvider rateProvider) { if (currency.equals(resultCurrency)) { return this; } double converted = rateProvider.convert(amount.doubleValue(), currency, resultCurrency); return Money.of(resultCurrency, converted); }
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "FX rate must be 1 when no conversion required") public void testConvertedToWithExplicitRateForSameCurrency() throws Exception { assertEquals(Money.of(Currency.RON, 200.23), MONEY_200_RON.convertedTo(CCY_RON, BigDecimal.valueOf(1.1))); }
@Test public void testConvertedToWithRateProvider() throws Exception { FxRateProvider provider = (ccy1, ccy2) -> 2.5d; assertEquals(Money.of(Currency.RON, 250.30), MONEY_100_AUD.convertedTo(CCY_RON, provider)); assertEquals(Money.of(Currency.RON, 200.23), MONEY_200_RON.convertedTo(CCY_RON, provider)); }