Commercial applications that aim to provide multi-currency functionality need a currency converter facility with access to up-to-date foreign exchange rates. This is what the CurrencyConverter class offers. Click here to download the CurrencyConverter.java source code.
static CurrencyConverter getInstance() Returns a singleton instance of CurrencyConverter.
double convert(double amount, java.lang.String fromCurrency, java.lang.String toCurrency) Converts a double precision floating point value from one currency to another. long convert(long amount, java.lang.String fromCurrency, java.lang.String toCurrency) Converts a long value from one currency to another. boolean isAvailable(java.lang.String currency) Check whether the exchange rate for a given currency is available. java.lang.String getCurrencies() Returns all currencies for which exchange rates are available. java.util.Date getReferenceDate() Get the reference date for the exchange rates as a Java Date. java.lang.String getCacheFileName() Get the name of the fully qualified path name of the XML cache file. void setCacheFileName(java.lang.String cacheFileName) Set the location where the XML cache file should be stored. void clearCache() Delete XML cache file and reset internal data structure.
The CurrencyConverter class provides an API for accessing the European Central Bank's (ECB) foreign exchange rates. The published ECB rates contain exchange rates for approx. 35 of the world's major currencies. They are updated daily at 14:15 CET. These rates use EUR as reference currency and are specified with a precision of 1/10000 of the currency unit (one hundredth cent). The convert() method performs currency conversions using either double values or 64-bit long integer values. Long values are preferred in order to avoid problems associated with floating point arithmetics. A local cache file is used for storing exchange rates to reduce network latency. The cache file is updated automatically when new exchange rates become available. It is created/updated the first time a call to convert() is made. By calling the clearCache() method before convert(), a reload of the exchange rates from the ECB server is forced. The CurrencyConverter class is implemented as a simple singleton; it is currently not thread-safe. It should be fairly easy to change it into a Java Bean, or to add code for sub-classing. Update Oct-2009: Manish Dubey has extended the CurrencyConverter class to access exchange rates up to 90 days in the past. With this extension, exchange rates for any currency can be retrieved with a specified date within the last 90 days. You can download the extended version here.