1 package org.apidesign.apifest08.currency;
4 import java.math.BigDecimal;
5 import java.math.MathContext;
6 import java.math.RoundingMode;
7 import java.util.Currency;
11 * Convert between two currencies.
13 * @author D'Arcy Smith
16 public final class Convertor
19 * The currency to cvonvert from.
21 private final Currency currencyA;
24 * The currency to cvonvert from.
26 private final Currency currencyB;
29 * Constructs a convertor with the specified currencies.
31 * @param a the currency to convert from.
32 * @param b the currency to convert to.
33 * @throws IllegalArgumentException if either a or b are null.
35 public Convertor(final Currency a,
40 throw new IllegalArgumentException("a cannot be null");
45 throw new IllegalArgumentException("a cannot be null");
53 * Convert from currency "b" to currency "a".
55 * @param amount the amount to convert.
56 * @return the converted amount.
57 * @throws IllegalArgumentException if amount is null.
59 public BigDecimal convertFrom(final BigDecimal amount)
61 final BigDecimal aInUSD;
62 final BigDecimal bInUSD;
63 final BigDecimal temp;
64 final BigDecimal result;
68 throw new IllegalArgumentException("amount cannot be null");
71 aInUSD = CurrencyValues.getValue(currencyA);
72 bInUSD = CurrencyValues.getValue(currencyB);
73 temp = amount.divide(bInUSD, MathContext.DECIMAL32);
74 result = temp.multiply(aInUSD);
76 return (result.setScale(2, RoundingMode.HALF_DOWN));
80 * Convert from currency "a" to currency "b".
82 * @param amount the amount to convert.
83 * @return the converted amount.
84 * @throws IllegalArgumentException if amount is null.
86 public BigDecimal convertTo(final BigDecimal amount)
88 final BigDecimal aInUSD;
89 final BigDecimal bInUSD;
90 final BigDecimal temp;
91 final BigDecimal result;
95 throw new IllegalArgumentException("amount cannot be null");
98 aInUSD = CurrencyValues.getValue(currencyA);
99 bInUSD = CurrencyValues.getValue(currencyB);
100 temp = amount.divide(aInUSD, MathContext.DECIMAL32);
101 result = temp.multiply(bInUSD);
103 return (result.setScale(2, RoundingMode.HALF_DOWN));