Currency Converter using Google API

Google API provides currency conversion rates.
For example, to convert 1 USD into Indonesian Rupiah (IDR), you can call Google API with the following format :
http://www.google.com/ig/calculator?hl=en&q=1USD=?IDR

URL above will return JSON objects below :
{lhs: "1 U.S. dollar",rhs: "9 523.80952 Indonesian rupiahs",error: "",icc: true}

The following code is an example how to get the value as a final result of the convertion :

public bool Convert(string baseCurrency, string targetCurrency, out double currencyRate)
        {
            try
            {
                string url = string.Format("http://www.google.com/ig/calculator?hl=en&q=1{0}%3D%3F{1}",  baseCurrency, targetCurrency);
                WebClient web = new WebClient();
                web.Encoding = System.Text.Encoding.ASCII;
                string response = web.DownloadString(url);
                Regex regex = new Regex("rhs: \\\"(\\d*.\\d*.\\d*)");
                Match match = regex.Match(response);
                string sRate = match.Groups[1].Value.ToString();
                sRate = sRate.Replace("?", "");
                currencyRate = System.Convert.ToDouble(sRate);
                currencyRate = Math.Round(currencyRate, 2);
            }
            catch(Exception)
            {
                currencyRate = 0;
                return false;
            }

            return true;
           
        }



Reference are System.Text.RegularExpressions, System.Net.WebClient, and System.Math.

Ok, may it helps,

Thanks

1 comment: