Chapter 9. Currencies, Currencies, Everywhere
Small change, small wonders—these are the currency of my endurance and ultimately of my life.Barbara Kingsolver
Here’s the current state of our evaluate feature vis-à-vis Money
entities in a Portfolio
:
-
When converting a
Money
in a currency to the same currency, it returns theamount
of theMoney
. This is correct: the exchange rate for any currency to itself is 1. -
In all other cases, the
amount
of theMoney
is multiplied by a fixed number (1.2). This is correct in a very limited sense: this rate ensures conversions from USD to EUR only. There is no way to modify this exchange rate or specify any other rate.
Our currency conversion code does one thing correctly and another thing almost correctly. It’s time to make it work correctly in both cases. In this chapter, we’ll introduce—at long last—the conversion of money from one currency into another using currency-specific exchange rates.
Making a Hash(map) of Things
What we need is a hashmap that allows us to look up exchange rates given a “from” currency and a “to” currency. The hashmap would be a representation of an exchange rate table we regularly see in banks and currency exchange counters at airports, as shown in Table 9-1.
From | To | Rate |
---|---|---|
EUR |
USD |
1.2 |
USD |
EUR |
0.82 |
USD |
KRW |
1100 |
KRW |
USD |
0.00090 |
EUR |
KRW |
1344 |
KRW |
EUR |
0.00073 |
To read this table, use this pattern: given an amount in the “from” currency, multiply by the “rate” to get ...
Get Learning Test-Driven Development now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.