As JavaScript has its quirks with floats (e.g. 0.1+0.2 is > 0.3 and similarly in divisions), how to deal with currency conversion? Usually currency conversion rates are in float going from 6 and more decimal points. Converting them from one currency to another and to another, seems highly prone to javascript float errors. While currency conversion is quite common task, I wonder how do people usually deal with this?
For now, I don't have any solution and not sure if it has caused issues in the past. Even if I had this issue, it is likely to be missed. I simply use whatever currency rates I have and multiply/divide to get the other currency. This is how I work with currencies at the moment
- Get the currency exchange rates for
USD
from a 3rd party API. Sample response{ base: 'USD', rates: { INR: 80.8653858542, GBP: ... } }
- I assume a dummy currency
XXX
to have a constant relationship withINR
e.g.1 XXX = 200 INR
. This rate never changes. I chose INR because this is my bank account currency. I use the dummy currency to make sure that I can always show a predictable amount to users irrespective of the exchange rates. - I use this dummy currency as a base currency. So whatever rates I received for
USD
from step 1, I convert it intoXXX
i.e.usdToXXX = usdToInr/200 = 80.8653858542/200 = 0.404326929271
and finally the rate card becomes ` { base: XXX, rates: { INR: 200, USD: 0.404326929271 } - Now for all the conversions, I use this rate card of XXX