Jarloo

Menu

Google Exchange Rate API

If you type “1 USD to CAD” into Google it will return the exchange rate for USD/CAD. This is a very cool feature, and like many of Googles features it’s available as an API for you to use.

The API is rest based and it returns a JSON object with the details.

To use the API you just need to do this:

http://www.google.com/ig/calculator?hl=en&q=1USD%3D%3FCAD

The number 1 before USD is the amount of dollars or quantity.

When you do this you get back the following JSON object:

{lhs: “2 U.S. dollars”,rhs: “1.89159282 Canadian dollars”,error: “”,icc: true}

As you can see the result is called rhs, but it combines the resulting value with the text “Canadian Dollars”. Not sure why Google would merge a decimal and string like that instead of making them discrete fields, but in our implementation we will remove the string and store the result as a decimal.

ExchangeRateCalculator

This class has just one method: Convert. It takes the amount of dollars to convert (could be fractional such as 1.25 etc..) and the from currency (USD) and the to currency (CAD).

using System.Net;
using System.Text.RegularExpressions;

namespace CurrencyConverter
{
    public static class ExchangeRateCalculator
    {
        public static decimal Convert(decimal amount, string fromCurrency, string toCurrency)
        {
            WebClient web = new WebClient();

            string url = string.Format("http://www.google.com/ig/calculator?hl=en&q={2}{0}%3D%3F{1}", fromCurrency.ToUpper(), toCurrency.ToUpper(), amount);

            string response = web.DownloadString(url);

            Regex regex = new Regex("rhs: "(d*.d*)");
            Match match = regex.Match(response);

            decimal rate = System.Convert.ToDecimal(match.Groups[1].Value);

            return rate;
        }
    }
}

Categories:   Finance

Comments

Sorry, comments are closed for this item.