Java Currency Conversion Example

In this example we are going to implement Currency Conversion Using Java.

For converting money from one currency to another, we need to find the exchange rate between that currencies.

Mostly exchange rates are fluctuating in daily basis. Here we are using Yahoo Finance API online service for finding exchange rates

You can see more features about the API here -> http://finance.yahoo.com/currency-converter

Java Currency Conversion Example

package com.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

public class JavaCurrencyConversionExample {

   
public static void main(String args[]) {

       
// converting 1000 Euro to US Dollar
       
System.out.println("Euro/US Dollar: " + findExchangeRateAndConvert("EUR", "USD", 1000));

       
// converting 1000 US Dollar to Euro
       
System.out.println("US Dollar/Euro: " + findExchangeRateAndConvert("USD", "EUR", 1000));

       
// converting 1000 US Dollar to Indian Rupee
       
System.out.println("US Dollar/Indian Rupee: " + findExchangeRateAndConvert("USD", "INR", 1000));

       
// converting 1000 Indian Rupee to US Dollar
       
System.out.println("Indian Rupee/US Dollar: " + findExchangeRateAndConvert("INR", "USD", 1000));
   
}
   
   
private static Double findExchangeRateAndConvert(String from, String to, int amount) {
       
try {
           
//Yahoo Finance API
           
URL url = new URL("http://finance.yahoo.com/d/quotes.csv?f=l1&s="+ from + to + "=X");
            BufferedReader reader =
new BufferedReader(new InputStreamReader(url.openStream()));
            String line = reader.readLine
();
           
if (line.length() > 0) {
               
return Double.parseDouble(line) * amount;
           
}
           
reader.close();
       
} catch (Exception e) {
           
System.out.println(e.getMessage());
       
}
       
return null;
   
}
}
Output
Euro/US Dollar: 1266.8999999999999
US Dollar/Euro: 789.3
US Dollar/Indian Rupee: 61350.0
Indian Rupee/US Dollar: 16.299999999999997

Yahoo Query Language Example

Yahoo Finance API also provides Yahoo Query Language, which helps to convert different currencies conversions at once in XML or JSON.

If you know that you need to convert "USD->EUR", "USD->JPY", "USD->INR" etc, then Yahoo Query Language will be the better choice, because we can get the response together in XML or JSON.

http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "USDJPY", "USDINR")&env=store://datatables.org/alltableswithkeys
Output
Java Currency Conversion Example





Your email address will not be published. Required fields are marked *