Currency Converter

Convert between major currencies.

Output will appear here.

For informational purposes only. Not financial advice. Consult a licensed advisor.

No data is stored or transmitted.

(function(){ const display = document.querySelector('.result'); const source = document.querySelector('#rate-source'); const amountEl = document.querySelector('[data-key="amount"]'); const fromEl = document.querySelector('#from'); const toEl = document.querySelector('#to'); let rates = null, loaded = false; const defaults = {USD:1,EUR:0.92,GBP:0.79,CAD:1.36,AUD:1.53,JPY:151.4,CNY:7.24,INR:83.5}; const fmt = (n) => { const v = Number(n); if(!Number.isFinite(v)) return ''; if(Math.abs(v) < 0.01 && v !== 0) return v.toFixed(6); return v.toLocaleString(undefined, {maximumFractionDigits: 4}); }; const convert = () => { let amount = Number(amountEl?.value || 0); const fromC = fromEl?.value || 'USD'; const toC = toEl?.value || 'USD'; if(!Number.isFinite(amount)) amount = 0; let rate = 1; if(rates && loaded){ rate = (rates[toC] || 1) / (rates[fromC] || 1); } else if(rates){ rate = (rates[toC] || 1) / (rates[fromC] || 1); } else { rate = (defaults[toC] || 1) / (defaults[fromC] || 1); } const out = amount * rate; if(display) display.textContent = fmt(out) + ' ' + toC; if(source) source.textContent = loaded ? 'Live API rates' : 'Offline fallback rates'; return out; }; const load = async () => { try { const res = await fetch('https://open.er-api.com/v6/latest/USD', {mode:'cors'}); if(!res.ok) throw new Error('request_failed'); const data = await res.json(); if(data?.rates){ rates = data.rates; loaded = true; convert(); } } catch(e){ convert(); } }; const bind = () => { [amountEl, fromEl, toEl].forEach(el => el?.addEventListener('input', convert)); [amountEl, fromEl, toEl].forEach(el => el?.addEventListener('change', convert)); }; if(document.readyState === 'loading'){ document.addEventListener('DOMContentLoaded', () => { load(); bind(); convert(); }); } else { load(); bind(); convert(); } })();