Click here to Skip to main content
Click here to Skip to main content

Free Exchanges - Add Currency Conversion to your web site - for free

, 26 Apr 2005 CPOL
Rate this:
Please Sign up or sign in to vote.
A simple inline ASPX page that can display prices in different currencies with daily updated exchange rates.

Sample Image

Currency conversion in action.

Introduction

This article describes a simple aspx page that displays prices in multiple currencies, using 'live' exchange rates. The exchange rates used are pulled from a public domain source that is updated daily. The page uses in-line code - so no DLL to distribute.

Background

When I started selling my own software, I wanted to make buying it as painless as possible. I also wanted to appeal to everyone who came to my web site - and not make potential customers reach for the calculator, just because they don't live in my country. I'm always surprised how many web sites still display their prices in one currency - usually US dollars.

At first, I thought PayPal would provide an answer as it has international features. Unfortunately, PayPal only supports a limited number of currencies, and there's a charge for currency conversions. If your native currency is non-US, and your largest market is the US, it can soon add up.

Instead, I decided to display an approximate price in the customer’s currency, along side the native-currency price. Then the customer knows roughly how much they were going to pay, but the transaction happens in the native currency, so no conversion charge.

Converting prices on the fly is easy, but I wanted the exchange rates to be dynamic.

There are several providers of exchange rates, but all the electronic feeds I could find needed to be paid for – and it seemed a lot for a number! I found articles on using Yahoo Finance’s RSS feed, but again, the legal small print made me nervous. There’s even a Code Project article on converting emails from XE.com, but I wanted something simpler.

This article describes my solution – pulling exchange rate information from a public-domain document at the European Central Bank, which is updated daily.

I’ve used the technique on my web site and it works well.

Enjoy!

Using the code

The sample page PricingDemo.aspx displays base prices and a combo box of currencies. Select a different currency and submit the page. The getConversionRate function looks up an exchange rate for the currency. The PrintPrice function returns a string containing the base price and the price in the selected currency.

To use the code on your page, copy the following block into your page:

<script language="VB" runat="server">

  'Load the conversion rate file
  Public Function getConversionRate(ByVal sFromCurr _
         As String, ByVal sToCurr As String) As Double
   Dim req As HttpWebRequest
   Dim res As HttpWebResponse
   Dim srExRateData As StreamReader
   Dim sExRateData As String
   Dim separator As Char() = ","
   Dim dRate = 0, dRate1, dRate2 As Double
   Dim oExRateData As System.Xml.XmlDocument

   Const sExRateSource As String = _
     "http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"

   Try
    oExRateData = New System.Xml.XmlDocument
    srExRateData = New _
      StreamReader(WebRequest.Create(sExRateSource)_
      .GetResponse().GetResponseStream(), _
      Encoding.ASCII)
    oExRateData.Load(srExRateData)
    srExRateData.Close()
    dRate1 = getEuroRate(oExRateData, sFromCurr)
    dRate2 = getEuroRate(oExRateData, sToCurr)
    dRate = dRate2 / dRate1
   Catch
   End Try
   Return dRate
  End Function

  'Get a rate note from the xml
  Function getEuroRate(ByRef oExRateData As _
    System.Xml.XmlDocument, ByVal sCurr As String) As Double

   Dim oExRateNode As System.Xml.XmlNode

   oExRateNode = oExRateData.SelectSingleNode("*/*/*/*[@currency='"_
                                                + sCurr + "']/@rate")
   If Not oExRateNode Is Nothing Then
     Return CDbl(oExRateNode.Value)
   Else
     Return 1
   End If
  End Function

 'Return the price
 Public Function PrintPrice(ByVal dPrice As Double, _
    ByVal dRate As Double, ByVal sCurr As String) As String

  Dim sReturn as string 

  if sCurr="USD" then sCurr="$US"
  if not sCurr="" then
    sReturn = (dRate * dPrice).ToString("#") & sCurr & "<sup>*</sup>  "
  end if
  sReturn += "GB£" & dPrice 
  return sReturn
 End Function

</script>
<%

 'Initialise exchange rates
 Dim sCurr as string ="USD" 'Default currency
 Dim oReqCurr as object =request("curr")
 if not oReqCurr is nothing then sCurr=oReqCurrr
 Dim dRate = getConversionRate("GBP",sCurr)
 Dim Price1 as string ="25.00" 
 Dim Price2 as string ="75.00"
 'End of initialisation
%>

Add the Change Currency combo and button by pasting the following into your page and changing the action of the FORM tag to point to that page.

<form method="post" action="ThisPage.aspx">
 <sup>*</sup> Approximate prices in my currency <br>
 <select name="curr">
  <option value="">Select Currency...</option>
  <Option Value="USD">US Dollar</Option>
  <Option Value="EUR">Euro</Option>
  <Option Value="JPY">Japanese Yen</Option>
  <Option Value="DKK">Danish Krone</Option>
  <Option Value="GBP">Pound Sterling</Option>
  <Option Value="SEK">Swedish Krona</Option>
  <Option Value="CHF">Swiss Franc</Option>
  <Option Value="ISK">Icelandic Krona</Option>
  <Option Value="NOK">Norwegian Krone</Option>
  <Option Value="BGN">Bulgarian Lev</Option>
  <Option Value="CYP">Cyprus Pound</Option>
  <Option Value="CZK">Czech Koruna</Option>
  <Option Value="EEK">Estonian Kroon</Option>
  <Option Value="HUF">Hungarian Forint</Option>
  <Option Value="LTL">Lithuanian Litas</Option>
  <Option Value="LVL">Latvian Lats</Option>
  <Option Value="MTL">Maltese Lira</Option>
  <Option Value="PLN">Polish Zloty</Option>
  <Option Value="ROL">Romanian Leu</Option>
  <Option Value="SIT">Slovenian Tolar</Option>
  <Option Value="SKK">Slovakian Koruna</Option>
  <Option Value="TRY">New Turkish Lira</Option>
  <Option Value="AUD">Australian Dollar</Option>
  <Option Value="CAD">Canadian Dollar</Option>
  <Option Value="HKD">Hong Kong Dollar</Option>
  <Option Value="NZD">New Zealand Dollar</Option>
  <Option Value="SGD">Singapore Dollar</Option>
  <Option Value="KRW">South Korean Won</Option>
  <Option Value="ZAR">South African Rand</Option>
 </select>
 <input type="submit"  value="Change Currency"  name="cmdChange">
</form>

Display a price using:

<%=PrintPrice(Price1,dRate,sCurr)%>

To add a PayPal button, use code like this:

<form target="paypal" 
  action="https://www.paypal.com/cgi-bin/webscr" method="post">

   <input type="image" 
      src="https://www.paypal.com/en_GB/i/btn/x-click-but22.gif" 
      border="0" name="submit" 
      alt="Make payments with PayPal - it's fast, free and secure!">
   <input type="hidden" name="add" value="1">
   <input type="hidden" name="cmd" value="_cart">
   <input type="hidden" name="business" value="<<<your PayPal email address>>>">
   <input type="hidden" name="item_name" value="<<Product Name>>">
   <input type="hidden" name="item_number" value="<<<Product Code>>>">
   <input type="hidden" name="amount" value="<%=GFLitePrice%>">
   <input type="hidden" name="no_note" value="1">
   <input type="hidden" name="currency_code" value="GBP">
</form>

Obviously, you can customise PrintPrice as you need.

How It Works

The page uses the European Central Bank’s daily exchange rate data, which is published in XML here.

The data set contains conversion rates from Euros. To convert, say, British Pounds to US Dollars, the getConversionRate function simply looks up the rate for Euros to Pounds, and the rate for Euros to Dollars, using getEuroRate. If you happen to be converting to or from Euros, getEuroRate returns 1, so one or other of the rates is ignored.

Missing Classic ASP?

ASP.NET is great, but sometimes, I pine for ASP classic. There’s something nice about being able to write a page without having to worry about compiling a DLL and uploading it, so I decided to use in-line code. There doesn’t seem to be much documentation on in-line code in aspx, but it’s easy.

The main ‘tricks’ are:

  1. Declare your functions in a <script language="VB" runat="server"> </script> block.
  2. Use <% ...... %> tags to insert code into the HTML, just like classic ASP.
  3. To get information posted from forms, use constructs like:
    Dim oReqCurr as object =request("curr")

More To Do

I don't like the idea that my web page won't show prices because the ECB website's thrown a tantrum. So I want to amend the code so that the XML is cached locally, and only updated if it’s a day out of date.

Your Comments Please

This is my first CodeProject article, and I'd appreciate your feedback. Good? Bad? Interesting? Useful? Made you laugh? Made you cry? Let me know please...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

robink
Web Developer
United Kingdom United Kingdom
I've been hunched over computer keyboards since 32K was an impressive ammount of RAM.
 
Been developing for cash since early versions of VB through ASP to .net. More recently I've been entering the slightly scary world that is Java.
 
My current pet product is GOFLOW. It's an automation package that allows users draw tasks made from a set of plug-in tools. Visit us at www.InTheGardenSoftware.com.

Comments and Discussions

 
Questionget exception PinmemberSergey Kofanov4-Sep-11 2:27 
QuestionMoney Conversion PinmemberMember 812351729-Jul-11 23:48 
GeneralVery useful! Thanks! PinmemberadamUK7-May-08 3:30 
GeneralASP Script version pls Pinmemberrvanhoeven2-May-07 8:32 
QuestionNice article but doesn't work PinmemberAshis Chankraborty2-Nov-06 5:04 
QuestionIt doesn't work for me. Pinmemberalexfromto24-Jan-06 14:26 
AnswerRe: It doesn't work for me. Pinmemberalexfromto24-Jan-06 14:28 
GeneralUseful Pinmemberterryrey22-Sep-05 5:50 
GeneralConversion broken on international platforms PinmemberMattias Åslund4-Jul-05 0:37 
GeneralFeedback Please Pinmemberrobink18-Mar-05 7:57 
GeneralRe: Feedback Please PinmemberLakshminarayanan26-Apr-05 5:56 
GeneralRe: Feedback Please PinmemberTCDooM3-May-05 21:57 
GeneralRe: Feedback Please PinsussChristopher Bergqvist31-Aug-05 9:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411022.1 | Last Updated 26 Apr 2005
Article Copyright 2005 by robink
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid