JavaScript Currency Converter: Live Exchange Rates Without Float Bugs
5 min read
A JavaScript currency converter looks like a ten-line job: fetch a rate, multiply, show the result. The ten lines work in a demo. In production they usually break in three places: the math uses floating-point numbers, the API key ends up in browser code, and nobody checks whether the rate is fresh.
This guide builds a small converter in Node.js (18 or later, which ships fetch) that avoids all three. You will see two approaches: letting the API do an exact conversion, and converting locally with BigInt when you need full control over rounding. The same ideas carry over to Deno, Bun and server-side TypeScript.
Why JavaScript numbers are the wrong tool for money
Every JavaScript Number is a 64-bit binary float. Many decimal values cannot be stored exactly in binary, so small errors appear:
0.1 + 0.2; // 0.30000000000000004
1.005 * 100; // 100.49999999999999
Math.round(1.005 * 100) / 100; // 1 (you probably expected 1.01)
One rounding error of a fraction of a cent is harmless. Thousands of invoice lines, refunds and ledger totals that disagree by a cent are not. We covered the general problem in currency conversion rounding without floating-point errors, and the rule is the same here: never let a money amount or a rate become a Number.
That is why GetRatesAPI returns rates and amounts as JSON strings, such as "rate":"1.0842". JSON.parse leaves strings alone, so the value arrives exactly as the API produced it. Your job is to keep it a string (or a scaled integer) until the moment you display it.
Approach 1: let the API convert
The simplest correct converter calls the convert endpoint. It multiplies exactly and returns converted_amount as a string, unrounded. Store your API key in an environment variable and send it in the Authorization header, as described in the authentication docs.
const BASE_URL = "https://api.getratesapi.com";
async function convert(from, to, amount) {
const query = new URLSearchParams({ from, to, amount });
const res = await fetch(`${BASE_URL}/v1/convert?${query}`, {
headers: { Authorization: `ApiKey ${process.env.GETRATES_API_KEY}` },
});
const body = await res.json();
if (!res.ok) {
throw Object.assign(new Error(body.message), {
code: body.code,
requestId: body.request_id,
});
}
return body;
}
const result = await convert("USD", "EUR", "125.50");
console.log(result.converted_amount); // a decimal string, not rounded
Pass amount as a string too. If you build it from user input, validate it first; a malformed amount returns invalid_amount (HTTP 400), which is not billed but still wastes a round trip.
Notice what is missing: no parseFloat, no toFixed, no Math.round. The result is a decimal string and you decide how to round it for display or for an invoice.
Approach 2: fetch the rate, convert locally with BigInt
Sometimes you want to convert many amounts with one rate: a cart with 40 line items, a report with thousands of rows, or a price list. Calling the API per amount is wasteful. Fetch the rate once with the current rate endpoint and do the multiplication yourself, still without floats.
The trick is to represent a decimal as an integer plus a scale. "125.50" becomes 12550n with scale 2. Multiplying two decimals is multiplying the integers and adding the scales. BigInt has no size limit, so nothing overflows or loses precision.
function parseDecimal(str) {
const m = /^(-?)(\d+)(?:\.(\d+))?$/.exec(str);
if (!m) throw new Error(`Invalid decimal: ${str}`);
const frac = m[3] ?? "";
const int = BigInt(m[2] + frac);
return { int: m[1] ? -int : int, scale: frac.length };
}
function multiply(a, b) {
return { int: a.int * b.int, scale: a.scale + b.scale };
}
// Round half away from zero to `places` decimals and format as a string.
function toFixedString({ int, scale }, places) {
let value = int;
let s = scale;
if (s > places) {
const factor = 10n ** BigInt(s - places);
const negative = value < 0n;
const abs = negative ? -value : value;
let q = abs / factor;
if ((abs % factor) * 2n >= factor) q += 1n;
value = negative ? -q : q;
s = places;
} else if (s < places) {
value *= 10n ** BigInt(places - s);
s = places;
}
const negative = value < 0n;
const digits = (negative ? -value : value).toString().padStart(s + 1, "0");
const whole = digits.slice(0, digits.length - s);
const fraction = digits.slice(digits.length - s);
return (negative ? "-" : "") + whole + (s > 0 ? "." + fraction : "");
}
Now combine it with a rate lookup. As a worked example with a made-up rate of 0.9223:
async function getRate(base, quote) {
const res = await fetch(`${BASE_URL}/v1/rates/${base}/${quote}`, {
headers: { Authorization: `ApiKey ${process.env.GETRATES_API_KEY}` },
});
const body = await res.json();
if (!res.ok) throw Object.assign(new Error(body.message), { code: body.code });
return body; // { base, quote, rate, as_of, status, type }
}
const { rate } = await getRate("USD", "EUR");
const prices = ["125.50", "19.99", "1049.00"];
const converted = prices.map((p) =>
toFixedString(multiply(parseDecimal(p), parseDecimal(rate)), 2)
);
With an example rate of "0.9223", 125.50 becomes 115.74865 internally and "115.75" after rounding to two places. Every step is exact until the single rounding at the end.
Use two decimals only for currencies that have two. JPY has none and some currencies have three, so look up the minor-unit count per currency rather than hard-coding 2.
Check status and as_of before you trust a rate
Every rate response includes as_of (when it was observed) and status ("fresh" or "stale"). Stale rates are flagged, not hidden, so the decision is yours:
function assertUsable(rateBody, { allowStale = false } = {}) {
if (rateBody.status === "stale" && !allowStale) {
const err = new Error(`Rate ${rateBody.base}/${rateBody.quote} is stale`);
err.code = "stale_rate"; // your own code, not an API error
err.asOf = rateBody.as_of;
throw err;
}
return rateBody;
}
A product page might accept a stale rate and show a small "prices updated at ..." note. A checkout that charges money might refuse, or fall back to the last rate you locked for that customer. Also look at type: a "derived" rate was calculated through USD, EUR or BTC, and its as_of is the oldest input. That is normal, and it is what lets any pair work even when no market quotes it directly. Our post on cross rates explains the math.
Handle errors and retries
Errors come back as JSON with code, message and request_id. Branch on code, never on the message text. The error reference lists them all; the ones a converter meets most often are:
| Code | HTTP | What to do |
|---|---|---|
invalid_asset_symbol | 400 | Fix the code; do not retry |
invalid_amount | 400 | Validate user input; do not retry |
unauthorized | 401 | Check the key and header format |
unsupported_pair | 404 | Show a "not available" message |
rate_limit_exceeded | 429 | Wait retry_after_seconds, then retry |
quota_exceeded | 429 | Monthly quota used up; retrying will not help |
temporarily_unavailable | 503 | Retry with backoff |
A small wrapper that retries only the retryable cases:
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function api(path, maxRetries = 2) {
for (let attempt = 0; ; attempt++) {
const res = await fetch(BASE_URL + path, {
headers: { Authorization: `ApiKey ${process.env.GETRATES_API_KEY}` },
});
const body = await res.json().catch(() => ({}));
if (res.ok) return body;
const retryable =
body.code === "rate_limit_exceeded" ||
body.code === "temporarily_unavailable";
if (retryable && attempt < maxRetries) {
const wait = body.retry_after_seconds ?? 2 ** attempt;
await sleep(wait * 1000);
continue;
}
throw Object.assign(new Error(body.message ?? `HTTP ${res.status}`), {
code: body.code,
requestId: body.request_id,
});
}
}
Log request_id with every failure; it makes support questions much easier. For a deeper treatment of backoff and limits, see handling rate limits and retries.
Keep the API key out of the browser
If your converter runs in a web page, do not call the API from client-side JavaScript with your key. Anyone can read it from the network tab. Instead:
- Create a small server route, for example
/api/convert, that holds the key in an environment variable. - Validate
from,toandamounton the server. - Call the API from there and return only what the page needs.
- Cache the rate briefly on the server so a busy page does not spend a request unit per visitor. Our guide to caching exchange rates without showing stale prices shows how to pick a time-to-live from the
statusandas_offields.
Fiat rates refresh every 60 seconds and crypto every 10 seconds, so caching for a few seconds to a minute loses very little accuracy. Keys can be rotated or revoked in the dashboard if one ever leaks.
A short checklist
- Keep rates and amounts as strings or
BigInt; convert to a display string only at the end. - Round once, at the end, using the currency's real number of decimal places.
- Check
statusand decide per use case whether stale is acceptable. - Match on error
code, retry only 429 rate limits and 503s. - Call the API from your server, not the browser.
Try it with your own key
You can run every example above on the free plan, which needs no credit card. Create an account, copy a key into GETRATES_API_KEY, and test the endpoints in the dashboard playground first. About 170 fiat currencies, gold, silver and thousands of crypto assets use the same endpoints, and the full list is on the currencies page.