Sunday, July 12, 2009

How to write C code to convert currency?

Having the following prototype:


float ForeignToDollars (float units, float conv);


how do i write C code that converts currency from pounds, kronors (to US dollars) etc?





the following info is #defined:


* 1.96109 dollars per British pound


* 0.15794 dollars per Swedish kronor


* 1.46785 dollars per Euro


* 0.04067 dollars per Russian Ruble

How to write C code to convert currency?
This is more of a math problem than programming. Let's consider today's rate: 1 British Pound = 1.9881 USD





The best way to think of conversion, is cancellation of currency units, as one might do in physics.





For example:


1.9881 USD per British Pound implies


1.9881 USD/British Pound





To convert from USD to British pounds, divide 1 USD by 1.9881 USD per British Pound:


1 USD / 1.9881 USD/British Pound


Gives us: 0.5030 British Pound (since the USD units cancel)





If you try this in a converter like: http://finance.yahoo.com/currency/conver... the math works out.





So for your case, the pseudocode could be:


float DollarsToForeign(float units, float conv){


return units * ((float)1 / conv));


}





Hope that helps


No comments:

Post a Comment