Skip to content

Instantly share code, notes, and snippets.

@lukencode
Created November 18, 2011 04:29
Show Gist options
  • Save lukencode/1375608 to your computer and use it in GitHub Desktop.
Save lukencode/1375608 to your computer and use it in GitHub Desktop.
format currency by code, get exchange rates
public static class CurrencyHelper
{
private static string _currencyRegex = "rhs: \\\"(\\d*.\\d*)";
// slightly modified from: http://www.ashishblog.com/blog/currency-exchange-rate-in-webpage-using-c-asp-net/
// Uses a google api which takes requests in this format: http://www.google.com/ig/calculator?hl=en&q=1AUD%3D%3FUSD
public static decimal Convert(decimal amount, string fromCurrency, string toCurrency)
{
var web = new WebClient();
var query = string.Format("{0}{1}%3D%3F{2}", amount, fromCurrency, toCurrency);
string url = "http://www.google.com/ig/calculator?hl=en&q=" + query;
string response = web.DownloadString(url);
//todo check for error
//find right hand side rate
var match = Regex.Match(response, _currencyRegex);
var rate = System.Convert.ToDecimal(match.Groups[1].Value);
return rate;
}
public static decimal ExchangeRate(string fromCurrency, string toCurrency)
{
return Convert(1, fromCurrency, toCurrency);
}
public static string Format(decimal amount, string currencyCode)
{
var culture = (from c in CultureInfo.GetCultures(CultureTypes.SpecificCultures)
let r = new RegionInfo(c.LCID)
where r != null
&& r.ISOCurrencySymbol.ToUpper() == currencyCode.ToUpper()
select c).FirstOrDefault();
if (culture == null)
return amount.ToString("0.00");
return string.Format(culture, "{0:C}", amount);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment