Main Content

Easy conversion - image formats, currencies and distances

Archive - Originally posted on "The Horse's Mouth" - 2008-05-21 08:31:37 - Graham Ellis

If you're converting between distances (inches, feet, metres, centimetres, metres, furlongs or perches), between currecies (dollars, euros, pounds, roubles, lira) or between graphic file formats (.jpg, .png, .gif, .xbm, .tiff), chances are you'll have any one of a large number of different inputs to change to any one of a large number of different outputs. With - for example - 10 currencies, you'll have 100 (one hundred) possible conversions - and the code will get much bigger and less practical with each new currency added.

The solution is to choose an intermediate standard - for example, to convert the incoming currency to the Euro, then from the Euro to the target currency. That reduces your 100 down to 20 conversions .... and if you had 20 currencies, it would reduce 400 down to 40.

I've got an illustrated example of this techinque on our PHP Techniques Workshop - source code here and the code may be run here. It's also in use on our hotel currency page if guests with to pay in Euros or Dollars - that's based on a more general exchange rate convertor here.

Please consider with this technique that you need to be careful to avoid a loss of precision / information at the intermediate stage.

If your intermediate graphic file standard was .jpg ... it would be a poor choice. .jpg is a lossy standard which makes some compromises. Similarly, an 8 bit image standard would not be suitable.

If your exchange rate tables include commission or are not mid-rate, once again the double conversion I advocate above would lead to an incorrectly rounded result with some loss of data or accuracy. (The ECB tables we use ARE midrate, so there's not an issue!)