A currency converter looks like one multiplication. Build one for real users and you hit the interesting parts: converting between two non-USD currencies, bad data from an API, an API that is down, and showing 15,000 JPY and 92,00 € the way people expect.
This post builds the core of one in plain JavaScript, with no libraries. Everything below was run in Node before I wrote it down, using mocked network calls. The finished tool is here: free online currency converter.
The one formula
Most free rate APIs give you a table of rates against a single base, usually USD:
const rates = { USD: 1, EUR: 0.92, GBP: 0.79, JPY: 150 }; To go from currency A to currency B, divide by A's rate (back to the base) and multiply by B's rate:
converted = amount * (rates[to] / rates[from]) That also handles cross rates like EUR to GBP without a direct EUR/GBP price: 100 EUR = 100 * (0.79 / 0.92) = 85.87 GBP.
Step 1: Convert, and refuse bad input
function convert(amount, from, to, rates) { if (!Number.isFinite(amount) || amount < 0) throw new Error("Enter a positive amount"); const a = rates[from], b = rates[to]; if (!(a > 0) || !(b > 0)) throw new Error(`No rate for ${!(a > 0) ? from : to}`); return amount * (b / a); } Two details matter. !(a > 0) catches undefined, NaN, 0 and negatives in one check, so you never divide by zero or return NaN to the screen. And throwing a clear message lets the UI show something useful instead of a blank box.
Step 2: Format with Intl, not toFixed
toFixed(2) is wrong for currencies that don't use two decimals (JPY has none) and it ignores local conventions. Intl.NumberFormat handles both:
function format(value, currency, locale = "en-US") { return new Intl.NumberFormat(locale, { style: "currency", currency }).format(value); } format(92, "EUR", "en-US"); // "€92.00" format(15000, "JPY", "en-US"); // "¥15,000" format(92, "EUR", "de-DE"); // "92,00 €" Step 3: Never trust the API response
APIs change, return partial data, or send 0 for a currency they can't price. One bad value would silently give wrong conversions, so validate before you use a table:
function validRates(map) { if (!map || typeof map !== "object") return false; const keys = Object.keys(map); if (keys.length < 10) return false; return keys.every((k) => /^[A-Z]{3}$/.test(k) && Number.isFinite(map[k]) && map[k] > 0) && map.USD === 1; } This rejects tables that are too small, have a non-code key, or contain a zero, a string or a missing base. It is cheap and has saved me from showing nonsense.
Step 4: Fall back between sources
Free APIs go down. Try sources in order and move on when one fails, times out or returns invalid data:
async function loadRates(sources, { fetchFn = fetch, timeoutMs = 8000 } = {}) { for (const s of sources) { try { const ctl = new AbortController(); const timer = setTimeout(() => ctl.abort(), timeoutMs); const res = await fetchFn(s.url, { signal: ctl.signal }); clearTimeout(timer); if (!res.ok) throw new Error("bad status"); const rates = s.pick(await res.json()); if (validRates(rates)) return { rates, source: s.name }; } catch (e) { /* try the next source */ } } return null; } Each source describes how to get a USD-based table out of its own response shape:
const sources = [ { name: "ExchangeRate-API", url: "https://open.er-api.com/v6/latest/USD", pick: (d) => d.rates }, { name: "ECB via Frankfurter", url: "https://api.frankfurter.dev/v1/latest?base=USD", pick: (d) => ({ USD: 1, ...d.rates }) }, ]; The second source doesn't include the base currency in its table, so pick adds USD: 1 itself. Passing fetchFn in as a parameter is what made this testable: I replaced the network with fake functions and checked all three paths.
What I tested
// source A works -> uses A and never calls B // source A throws -> falls back to B // a table with EUR: 0, or an HTTP error from every source -> returns null convert(100, "USD", "EUR", base); // 92 convert(100, "EUR", "GBP", base); // 85.8696... convert(-5, "USD", "EUR", base); // throws "Enter a positive amount" convert(5, "USD", "XXX", base); // throws "No rate for XXX" Be honest about what the rate is
The rate in these APIs is a mid-market reference rate, the midpoint between buy and sell prices, updated about once a day. It is not what a bank or card will give you. Banks add a margin, and cards or transfer services may add fees on top. If you build a converter for real people, say that on the page, show the date of the rate, and say clearly when you are using a stale or fallback table.
Where to take it next
- Cache the table in
localStoragewith a timestamp, and reuse it for a few hours so you don't call the API on every visit. - A bundled fallback table so the tool still works offline, labelled as approximate.
- A swap button and remembering the last pair.
- Currencies with different decimals:
Intlhandles display, but round only at the end, never between steps.
If you want to see this in a finished interface, with 40 currencies, a swap button and an explanation of margins and fees, the currency converter has them, along with a guide to how exchange rates work. I build the tools on ToolPond as a solo developer, and I'd welcome bug reports from anyone who finds a wrong conversion.


