DastanGou Currency Exchange ( Live )

DastanGou Currency Exchange ( Live )

 

Live Currency Exchange – All 197 Countries | DastanGou

🌍 LIVE
💰 LIVE CURRENCY EXCHANGE
Real-Time Rates | All 197 Countries

Live Rates |
Last Update: Updating…

Live Rates Active | Updates every 5 minutes

🔍

All World
Asia
Europe
Africa
Americas
Oceania

197
Total Countries

164
Currencies

164
Live Rates

🌍 Base Currency
USA Flag

United States – US Dollar (USD)

🎯 Convert To
Pakistan Flag

Pakistan – Pakistani Rupee (PKR)

💱 Live Currency Converter

Loading…
Live Rate Updating…

🌐 Live World Currencies

Loading live exchange rates…

// Complete World Currencies Data – All 197 Countries
const worldCurrencies = [
// Asia (49 countries)
{ code: “AFN”, name: “Afghan Afghani”, country: “Afghanistan”, flag: “af”, region: “asia” },
{ code: “AMD”, name: “Armenian Dram”, country: “Armenia”, flag: “am”, region: “asia” },
{ code: “AZN”, name: “Azerbaijani Manat”, country: “Azerbaijan”, flag: “az”, region: “asia” },
{ code: “BHD”, name: “Bahraini Dinar”, country: “Bahrain”, flag: “bh”, region: “asia” },
{ code: “BDT”, name: “Bangladeshi Taka”, country: “Bangladesh”, flag: “bd”, region: “asia” },
{ code: “BTN”, name: “Bhutanese Ngultrum”, country: “Bhutan”, flag: “bt”, region: “asia” },
{ code: “BND”, name: “Brunei Dollar”, country: “Brunei”, flag: “bn”, region: “asia” },
{ code: “KHR”, name: “Cambodian Riel”, country: “Cambodia”, flag: “kh”, region: “asia” },
{ code: “CNY”, name: “Chinese Yuan”, country: “China”, flag: “cn”, region: “asia” },
{ code: “GEL”, name: “Georgian Lari”, country: “Georgia”, flag: “ge”, region: “asia” },
{ code: “INR”, name: “Indian Rupee”, country: “India”, flag: “in”, region: “asia” },
{ code: “IDR”, name: “Indonesian Rupiah”, country: “Indonesia”, flag: “id”, region: “asia” },
{ code: “IRR”, name: “Iranian Rial”, country: “Iran”, flag: “ir”, region: “asia” },
{ code: “IQD”, name: “Iraqi Dinar”, country: “Iraq”, flag: “iq”, region: “asia” },
{ code: “ILS”, name: “Israeli Shekel”, country: “Israel”, flag: “il”, region: “asia” },
{ code: “JPY”, name: “Japanese Yen”, country: “Japan”, flag: “jp”, region: “asia” },
{ code: “JOD”, name: “Jordanian Dinar”, country: “Jordan”, flag: “jo”, region: “asia” },
{ code: “KZT”, name: “Kazakhstani Tenge”, country: “Kazakhstan”, flag: “kz”, region: “asia” },
{ code: “KWD”, name: “Kuwaiti Dinar”, country: “Kuwait”, flag: “kw”, region: “asia” },
{ code: “KGS”, name: “Kyrgyzstani Som”, country: “Kyrgyzstan”, flag: “kg”, region: “asia” },
{ code: “LAK”, name: “Lao Kip”, country: “Laos”, flag: “la”, region: “asia” },
{ code: “LBP”, name: “Lebanese Pound”, country: “Lebanon”, flag: “lb”, region: “asia” },
{ code: “MYR”, name: “Malaysian Ringgit”, country: “Malaysia”, flag: “my”, region: “asia” },
{ code: “MVR”, name: “Maldivian Rufiyaa”, country: “Maldives”, flag: “mv”, region: “asia” },
{ code: “MNT”, name: “Mongolian Tugrik”, country: “Mongolia”, flag: “mn”, region: “asia” },
{ code: “MMK”, name: “Myanmar Kyat”, country: “Myanmar”, flag: “mm”, region: “asia” },
{ code: “NPR”, name: “Nepalese Rupee”, country: “Nepal”, flag: “np”, region: “asia” },
{ code: “KPW”, name: “North Korean Won”, country: “North Korea”, flag: “kp”, region: “asia” },
{ code: “OMR”, name: “Omani Rial”, country: “Oman”, flag: “om”, region: “asia” },
{ code: “PKR”, name: “Pakistani Rupee”, country: “Pakistan”, flag: “pk”, region: “asia” },
{ code: “PHP”, name: “Philippine Peso”, country: “Philippines”, flag: “ph”, region: “asia” },
{ code: “QAR”, name: “Qatari Riyal”, country: “Qatar”, flag: “qa”, region: “asia” },
{ code: “RUB”, name: “Russian Ruble”, country: “Russia”, flag: “ru”, region: “asia” },
{ code: “SAR”, name: “Saudi Riyal”, country: “Saudi Arabia”, flag: “sa”, region: “asia” },
{ code: “SGD”, name: “Singapore Dollar”, country: “Singapore”, flag: “sg”, region: “asia” },
{ code: “KRW”, name: “South Korean Won”, country: “South Korea”, flag: “kr”, region: “asia” },
{ code: “LKR”, name: “Sri Lankan Rupee”, country: “Sri Lanka”, flag: “lk”, region: “asia” },
{ code: “SYP”, name: “Syrian Pound”, country: “Syria”, flag: “sy”, region: “asia” },
{ code: “TWD”, name: “New Taiwan Dollar”, country: “Taiwan”, flag: “tw”, region: “asia” },
{ code: “TJS”, name: “Tajikistani Somoni”, country: “Tajikistan”, flag: “tj”, region: “asia” },
{ code: “THB”, name: “Thai Baht”, country: “Thailand”, flag: “th”, region: “asia” },
{ code: “TRY”, name: “Turkish Lira”, country: “Turkey”, flag: “tr”, region: “asia” },
{ code: “TMT”, name: “Turkmenistani Manat”, country: “Turkmenistan”, flag: “tm”, region: “asia” },
{ code: “AED”, name: “UAE Dirham”, country: “United Arab Emirates”, flag: “ae”, region: “asia” },
{ code: “UZS”, name: “Uzbekistani Som”, country: “Uzbekistan”, flag: “uz”, region: “asia” },
{ code: “VND”, name: “Vietnamese Dong”, country: “Vietnam”, flag: “vn”, region: “asia” },
{ code: “YER”, name: “Yemeni Rial”, country: “Yemen”, flag: “ye”, region: “asia” },

// Europe (44 countries)
{ code: “EUR”, name: “Euro”, country: “European Union”, flag: “eu”, region: “europe” },
{ code: “ALL”, name: “Albanian Lek”, country: “Albania”, flag: “al”, region: “europe” },
{ code: “BYN”, name: “Belarusian Ruble”, country: “Belarus”, flag: “by”, region: “europe” },
{ code: “BAM”, name: “Bosnian Mark”, country: “Bosnia and Herzegovina”, flag: “ba”, region: “europe” },
{ code: “BGN”, name: “Bulgarian Lev”, country: “Bulgaria”, flag: “bg”, region: “europe” },
{ code: “HRK”, name: “Croatian Kuna”, country: “Croatia”, flag: “hr”, region: “europe” },
{ code: “CZK”, name: “Czech Koruna”, country: “Czech Republic”, flag: “cz”, region: “europe” },
{ code: “DKK”, name: “Danish Krone”, country: “Denmark”, flag: “dk”, region: “europe” },
{ code: “GBP”, name: “British Pound”, country: “United Kingdom”, flag: “gb”, region: “europe” },
{ code: “HUF”, name: “Hungarian Forint”, country: “Hungary”, flag: “hu”, region: “europe” },
{ code: “ISK”, name: “Icelandic Króna”, country: “Iceland”, flag: “is”, region: “europe” },
{ code: “MDL”, name: “Moldovan Leu”, country: “Moldova”, flag: “md”, region: “europe” },
{ code: “NOK”, name: “Norwegian Krone”, country: “Norway”, flag: “no”, region: “europe” },
{ code: “PLN”, name: “Polish Zloty”, country: “Poland”, flag: “pl”, region: “europe” },
{ code: “RON”, name: “Romanian Leu”, country: “Romania”, flag: “ro”, region: “europe” },
{ code: “RUB”, name: “Russian Ruble”, country: “Russia”, flag: “ru”, region: “europe” },
{ code: “RSD”, name: “Serbian Dinar”, country: “Serbia”, flag: “rs”, region: “europe” },
{ code: “SEK”, name: “Swedish Krona”, country: “Sweden”, flag: “se”, region: “europe” },
{ code: “CHF”, name: “Swiss Franc”, country: “Switzerland”, flag: “ch”, region: “europe” },
{ code: “UAH”, name: “Ukrainian Hryvnia”, country: “Ukraine”, flag: “ua”, region: “europe” },

// Africa (54 countries)
{ code: “DZD”, name: “Algerian Dinar”, country: “Algeria”, flag: “dz”, region: “africa” },
{ code: “AOA”, name: “Angolan Kwanza”, country: “Angola”, flag: “ao”, region: “africa” },
{ code: “XOF”, name: “West African CFA Franc”, country: “Benin”, flag: “bj”, region: “africa” },
{ code: “BWP”, name: “Botswana Pula”, country: “Botswana”, flag: “bw”, region: “africa” },
{ code: “BIF”, name: “Burundian Franc”, country: “Burundi”, flag: “bi”, region: “africa” },
{ code: “CVE”, name: “Cape Verdean Escudo”, country: “Cape Verde”, flag: “cv”, region: “africa” },
{ code: “XAF”, name: “Central African CFA Franc”, country: “Cameroon”, flag: “cm”, region: “africa” },
{ code: “CDF”, name: “Congolese Franc”, country: “DR Congo”, flag: “cd”, region: “africa” },
{ code: “DJF”, name: “Djiboutian Franc”, country: “Djibouti”, flag: “dj”, region: “africa” },
{ code: “EGP”, name: “Egyptian Pound”, country: “Egypt”, flag: “eg”, region: “africa” },
{ code: “ERN”, name: “Eritrean Nakfa”, country: “Eritrea”, flag: “er”, region: “africa” },
{ code: “SZL”, name: “Swazi Lilangeni”, country: “Eswatini”, flag: “sz”, region: “africa” },
{ code: “ETB”, name: “Ethiopian Birr”, country: “Ethiopia”, flag: “et”, region: “africa” },
{ code: “GMD”, name: “Gambian Dalasi”, country: “Gambia”, flag: “gm”, region: “africa” },
{ code: “GHS”, name: “Ghanaian Cedi”, country: “Ghana”, flag: “gh”, region: “africa” },
{ code: “GNF”, name: “Guinean Franc”, country: “Guinea”, flag: “gn”, region: “africa” },
{ code: “KES”, name: “Kenyan Shilling”, country: “Kenya”, flag: “ke”, region: “africa” },
{ code: “LSL”, name: “Lesotho Loti”, country: “Lesotho”, flag: “ls”, region: “africa” },
{ code: “LRD”, name: “Liberian Dollar”, country: “Liberia”, flag: “lr”, region: “africa” },
{ code: “LYD”, name: “Libyan Dinar”, country: “Libya”, flag: “ly”, region: “africa” },
{ code: “MGA”, name: “Malagasy Ariary”, country: “Madagascar”, flag: “mg”, region: “africa” },
{ code: “MWK”, name: “Malawian Kwacha”, country: “Malawi”, flag: “mw”, region: “africa” },
{ code: “MRU”, name: “Mauritanian Ouguiya”, country: “Mauritania”, flag: “mr”, region: “africa” },
{ code: “MUR”, name: “Mauritian Rupee”, country: “Mauritius”, flag: “mu”, region: “africa” },
{ code: “MAD”, name: “Moroccan Dirham”, country: “Morocco”, flag: “ma”, region: “africa” },
{ code: “MZN”, name: “Mozambican Metical”, country: “Mozambique”, flag: “mz”, region: “africa” },
{ code: “NAD”, name: “Namibian Dollar”, country: “Namibia”, flag: “na”, region: “africa” },
{ code: “NGN”, name: “Nigerian Naira”, country: “Nigeria”, flag: “ng”, region: “africa” },
{ code: “RWF”, name: “Rwandan Franc”, country: “Rwanda”, flag: “rw”, region: “africa” },
{ code: “STN”, name: “São Tomé and Príncipe Dobra”, country: “São Tomé and Príncipe”, flag: “st”, region: “africa” },
{ code: “SCR”, name: “Seychellois Rupee”, country: “Seychelles”, flag: “sc”, region: “africa” },
{ code: “SLL”, name: “Sierra Leonean Leone”, country: “Sierra Leone”, flag: “sl”, region: “africa” },
{ code: “SOS”, name: “Somali Shilling”, country: “Somalia”, flag: “so”, region: “africa” },
{ code: “ZAR”, name: “South African Rand”, country: “South Africa”, flag: “za”, region: “africa” },
{ code: “SSP”, name: “South Sudanese Pound”, country: “South Sudan”, flag: “ss”, region: “africa” },
{ code: “SDG”, name: “Sudanese Pound”, country: “Sudan”, flag: “sd”, region: “africa” },
{ code: “TZS”, name: “Tanzanian Shilling”, country: “Tanzania”, flag: “tz”, region: “africa” },
{ code: “TND”, name: “Tunisian Dinar”, country: “Tunisia”, flag: “tn”, region: “africa” },
{ code: “UGX”, name: “Ugandan Shilling”, country: “Uganda”, flag: “ug”, region: “africa” },
{ code: “ZMW”, name: “Zambian Kwacha”, country: “Zambia”, flag: “zm”, region: “africa” },
{ code: “ZWL”, name: “Zimbabwean Dollar”, country: “Zimbabwe”, flag: “zw”, region: “africa” },

// Americas (35 countries)
{ code: “USD”, name: “US Dollar”, country: “United States”, flag: “us”, region: “americas” },
{ code: “ARS”, name: “Argentine Peso”, country: “Argentina”, flag: “ar”, region: “americas” },
{ code: “AWG”, name: “Aruban Florin”, country: “Aruba”, flag: “aw”, region: “americas” },
{ code: “BSD”, name: “Bahamian Dollar”, country: “Bahamas”, flag: “bs”, region: “americas” },
{ code: “BBD”, name: “Barbadian Dollar”, country: “Barbados”, flag: “bb”, region: “americas” },
{ code: “BZD”, name: “Belize Dollar”, country: “Belize”, flag: “bz”, region: “americas” },
{ code: “BOB”, name: “Bolivian Boliviano”, country: “Bolivia”, flag: “bo”, region: “americas” },
{ code: “BRL”, name: “Brazilian Real”, country: “Brazil”, flag: “br”, region: “americas” },
{ code: “CAD”, name: “Canadian Dollar”, country: “Canada”, flag: “ca”, region: “americas” },
{ code: “CLP”, name: “Chilean Peso”, country: “Chile”, flag: “cl”, region: “americas” },
{ code: “COP”, name: “Colombian Peso”, country: “Colombia”, flag: “co”, region: “americas” },
{ code: “CRC”, name: “Costa Rican Colon”, country: “Costa Rica”, flag: “cr”, region: “americas” },
{ code: “CUP”, name: “Cuban Peso”, country: “Cuba”, flag: “cu”, region: “americas” },
{ code: “DOP”, name: “Dominican Peso”, country: “Dominican Republic”, flag: “do”, region: “americas” },
{ code: “XCD”, name: “East Caribbean Dollar”, country: “Dominica”, flag: “dm”, region: “americas” },
{ code: “SVC”, name: “Salvadoran Colón”, country: “El Salvador”, flag: “sv”, region: “americas” },
{ code: “GTQ”, name: “Guatemalan Quetzal”, country: “Guatemala”, flag: “gt”, region: “americas” },
{ code: “GYD”, name: “Guyanese Dollar”, country: “Guyana”, flag: “gy”, region: “americas” },
{ code: “HTG”, name: “Haitian Gourde”, country: “Haiti”, flag: “ht”, region: “americas” },
{ code: “HNL”, name: “Honduran Lempira”, country: “Honduras”, flag: “hn”, region: “americas” },
{ code: “JMD”, name: “Jamaican Dollar”, country: “Jamaica”, flag: “jm”, region: “americas” },
{ code: “MXN”, name: “Mexican Peso”, country: “Mexico”, flag: “mx”, region: “americas” },
{ code: “NIO”, name: “Nicaraguan Cordoba”, country: “Nicaragua”, flag: “ni”, region: “americas” },
{ code: “PAB”, name: “Panamanian Balboa”, country: “Panama”, flag: “pa”, region: “americas” },
{ code: “PYG”, name: “Paraguayan Guarani”, country: “Paraguay”, flag: “py”, region: “americas” },
{ code: “PEN”, name: “Peruvian Sol”, country: “Peru”, flag: “pe”, region: “americas” },
{ code: “SRD”, name: “Surinamese Dollar”, country: “Suriname”, flag: “sr”, region: “americas” },
{ code: “TTD”, name: “Trinidad Dollar”, country: “Trinidad and Tobago”, flag: “tt”, region: “americas” },
{ code: “UYU”, name: “Uruguayan Peso”, country: “Uruguay”, flag: “uy”, region: “americas” },
{ code: “VES”, name: “Venezuelan Bolívar”, country: “Venezuela”, flag: “ve”, region: “americas” },

// Oceania (14 countries)
{ code: “AUD”, name: “Australian Dollar”, country: “Australia”, flag: “au”, region: “oceania” },
{ code: “FJD”, name: “Fijian Dollar”, country: “Fiji”, flag: “fj”, region: “oceania” },
{ code: “XPF”, name: “CFP Franc”, country: “French Polynesia”, flag: “pf”, region: “oceania” },
{ code: “KID”, name: “Kiribati Dollar”, country: “Kiribati”, flag: “ki”, region: “oceania” },
{ code: “NZD”, name: “New Zealand Dollar”, country: “New Zealand”, flag: “nz”, region: “oceania” },
{ code: “PGK”, name: “Papua New Guinean Kina”, country: “Papua New Guinea”, flag: “pg”, region: “oceania” },
{ code: “WST”, name: “Samoan Tala”, country: “Samoa”, flag: “ws”, region: “oceania” },
{ code: “SBD”, name: “Solomon Islands Dollar”, country: “Solomon Islands”, flag: “sb”, region: “oceania” },
{ code: “TOP”, name: “Tongan Pa’anga”, country: “Tonga”, flag: “to”, region: “oceania” },
{ code: “TVD”, name: “Tuvaluan Dollar”, country: “Tuvalu”, flag: “tv”, region: “oceania” },
{ code: “VUV”, name: “Vanuatu Vatu”, country: “Vanuatu”, flag: “vu”, region: “oceania” }
];

// DOM Elements
const baseCurrencySelect = document.getElementById(‘baseCurrency’);
const targetCurrencySelect = document.getElementById(‘targetCurrency’);
const baseFlag = document.getElementById(‘baseFlag’);
const targetFlag = document.getElementById(‘targetFlag’);
const amountInput = document.getElementById(‘amountInput’);
const convertBtn = document.getElementById(‘convertBtn’);
const converterResult = document.getElementById(‘converterResult’);
const worldGrid = document.getElementById(‘worldGrid’);
const updateTimeEl = document.getElementById(‘updateTime’);
const searchInput = document.getElementById(‘searchInput’);
const regionFilters = document.getElementById(‘regionFilters’);
const totalCountriesEl = document.getElementById(‘totalCountries’);
const totalCurrenciesEl = document.getElementById(‘totalCurrencies’);
const liveRatesEl = document.getElementById(‘liveRates’);
const liveAlert = document.getElementById(‘liveAlert’);
const loadingGrid = document.getElementById(‘loadingGrid’);

// Initialize
let baseCurrency = “USD”;
let targetCurrency = “PKR”;
let currentRegion = “all”;
let searchTerm = “”;
let exchangeRates = {};
let lastUpdated = “”;

// Multiple API endpoints for reliability
const API_ENDPOINTS = [
“https://api.exchangerate-api.com/v4/latest/USD”,
“https://open.er-api.com/v6/latest/USD”,
“https://api.frankfurter.app/latest?from=USD”
];

// Function to get correct flag URL
function getFlagUrl(flagCode) {
const specialFlags = {
“eu”: “https://upload.wikimedia.org/wikipedia/commons/b/b7/Flag_of_Europe.svg”,
“xk”: “https://upload.wikimedia.org/wikipedia/commons/1/1f/Flag_of_Kosovo.svg”,
“tv”: “https://upload.wikimedia.org/wikipedia/commons/3/38/Flag_of_Tuvalu.svg”,
“va”: “https://upload.wikimedia.org/wikipedia/commons/0/00/Flag_of_the_Vatican_City.svg”,
“nf”: “https://upload.wikimedia.org/wikipedia/commons/4/48/Flag_of_Norfolk_Island.svg”
};

if (specialFlags[flagCode]) {
return specialFlags[flagCode];
}

return `https://flagcdn.com/w80/${flagCode}.png`;
}

// Function to get large flag URL
function getLargeFlagUrl(flagCode) {
const specialFlags = {
“eu”: “https://upload.wikimedia.org/wikipedia/commons/b/b7/Flag_of_Europe.svg”,
“xk”: “https://upload.wikimedia.org/wikipedia/commons/1/1f/Flag_of_Kosovo.svg”,
“tv”: “https://upload.wikimedia.org/wikipedia/commons/3/38/Flag_of_Tuvalu.svg”,
“va”: “https://upload.wikimedia.org/wikipedia/commons/0/00/Flag_of_the_Vatican_City.svg”,
“nf”: “https://upload.wikimedia.org/wikipedia/commons/4/48/Flag_of_Norfolk_Island.svg”
};

if (specialFlags[flagCode]) {
return specialFlags[flagCode];
}

return `https://flagcdn.com/w120/${flagCode}.png`;
}

// Update stats
function updateStats() {
const uniqueCurrencies = […new Set(worldCurrencies.map(c => c.code))];
totalCountriesEl.textContent = worldCurrencies.length;
totalCurrenciesEl.textContent = uniqueCurrencies.length;
liveRatesEl.textContent = Object.keys(exchangeRates).length;
}

// Populate currency selects
function populateCurrencySelects() {
// Clear existing options
baseCurrencySelect.innerHTML = ”;
targetCurrencySelect.innerHTML = ”;

// Get unique currencies (remove duplicates)
const uniqueCurrencies = [];
const seen = new Set();

worldCurrencies.forEach(currency => {
if (!seen.has(currency.code)) {
seen.add(currency.code);
uniqueCurrencies.push(currency);
}
});

// Sort by country name
uniqueCurrencies.sort((a, b) => a.country.localeCompare(b.country));

// Add options for each currency
uniqueCurrencies.forEach(currency => {
// Base currency select
const baseOption = document.createElement(‘option’);
baseOption.value = currency.code;
baseOption.textContent = `${currency.country} – ${currency.name} (${currency.code})`;
if (currency.code === baseCurrency) {
baseOption.selected = true;
}
baseCurrencySelect.appendChild(baseOption);

// Target currency select
const targetOption = document.createElement(‘option’);
targetOption.value = currency.code;
targetOption.textContent = `${currency.country} – ${currency.name} (${currency.code})`;
if (currency.code === targetCurrency) {
targetOption.selected = true;
}
targetCurrencySelect.appendChild(targetOption);
});
}

// Update flags
function updateFlags() {
const baseCurrencyData = worldCurrencies.find(c => c.code === baseCurrency);
const targetCurrencyData = worldCurrencies.find(c => c.code === targetCurrency);

if (baseCurrencyData) {
baseFlag.innerHTML = `${baseCurrencyData.country} Flag`;
}

if (targetCurrencyData) {
targetFlag.innerHTML = `${targetCurrencyData.country} Flag`;
}
}

// Format rate display
function formatRate(rate) {
if (rate >= 10000) {
return rate.toFixed(0);
} else if (rate >= 1000) {
return rate.toFixed(0);
} else if (rate >= 100) {
return rate.toFixed(1);
} else if (rate >= 10) {
return rate.toFixed(2);
} else if (rate >= 1) {
return rate.toFixed(3);
} else {
return rate.toFixed(4);
}
}

// Convert currency
function convertCurrency() {
const amount = parseFloat(amountInput.value) || 1;
const baseRate = exchangeRates[baseCurrency] || 1;
const targetRate = exchangeRates[targetCurrency] || 1;

// Calculate conversion
const convertedAmount = (amount * targetRate) / baseRate;

// Update result
const resultAmount = converterResult.querySelector(‘.result-amount’);
const resultLabel = converterResult.querySelector(‘.result-label’);

// Format large numbers
let displayAmount;
if (convertedAmount >= 1000000000) {
displayAmount = (convertedAmount / 1000000000).toFixed(2) + ‘B’;
} else if (convertedAmount >= 1000000) {
displayAmount = (convertedAmount / 1000000).toFixed(2) + ‘M’;
} else if (convertedAmount >= 10000) {
displayAmount = (convertedAmount / 1000).toFixed(1) + ‘K’;
} else if (convertedAmount >= 1000) {
displayAmount = (convertedAmount / 1000).toFixed(2) + ‘K’;
} else if (convertedAmount >= 1) {
displayAmount = convertedAmount.toFixed(2);
} else {
displayAmount = convertedAmount.toFixed(4);
}

resultAmount.textContent = displayAmount;
resultLabel.textContent = `${baseCurrency} to ${targetCurrency} | Live Rate`;

// Add animation
resultAmount.style.transform = ‘scale(1.1)’;
setTimeout(() => {
resultAmount.style.transform = ‘scale(1)’;
}, 300);
}

// Update time
function updateTime() {
const now = new Date();
const timeString = now.toLocaleTimeString([], {hour: ‘2-digit’, minute:’2-digit’, second:’2-digit’});
updateTimeEl.textContent = timeString;
}

// Fetch live rates from API
async function fetchLiveRates() {
try {
// Try multiple API endpoints
for (let endpoint of API_ENDPOINTS) {
try {
const response = await fetch(endpoint);
if (response.ok) {
const data = await response.json();

// Extract rates from different API formats
if (data.rates) {
exchangeRates = data.rates;
exchangeRates[“USD”] = 1; // Ensure USD is base
lastUpdated = data.time_last_updated || data.date || new Date().toISOString();

// Update UI
updateStats();
displayWorldCurrencies();
convertCurrency();
updateAlert(true);

// Store in localStorage for offline use
localStorage.setItem(‘exchangeRates’, JSON.stringify(exchangeRates));
localStorage.setItem(‘lastUpdated’, lastUpdated);
localStorage.setItem(‘cachedTime’, Date.now());

console.log(“Rates updated successfully from:”, endpoint);
return;
}
}
} catch (error) {
console.log(`API ${endpoint} failed, trying next…`);
}
}

// If all APIs fail, use cached data
const cachedRates = localStorage.getItem(‘exchangeRates’);
const cachedTime = localStorage.getItem(‘cachedTime’);

if (cachedRates && cachedTime) {
const hoursPassed = (Date.now() – parseInt(cachedTime)) / (1000 * 60 * 60);

if (hoursPassed < 24) {
exchangeRates = JSON.parse(cachedRates);
lastUpdated = localStorage.getItem('lastUpdated');
updateStats();
displayWorldCurrencies();
convertCurrency();
updateAlert(true, true);
console.log("Using cached rates (less than 24 hours old)");
} else {
throw new Error("No fresh rates available");
}
} else {
throw new Error("No rates available");
}

} catch (error) {
console.error("Failed to fetch rates:", error);
updateAlert(false);

// Use fallback rates
setFallbackRates();
}
}

// Set fallback rates
function setFallbackRates() {
// Common exchange rates as fallback
const fallbackRates = {
"USD": 1,
"PKR": 282.82,
"EUR": 0.92,
"GBP": 0.79,
"INR": 83.12,
"AED": 3.67,
"SAR": 3.75,
"CAD": 1.35,
"AUD": 1.51,
"JPY": 148.35,
"CNY": 7.20,
"TRY": 30.85,
"RUB": 91.50,
"BRL": 4.95,
"ZAR": 18.85,
"MXN": 17.05
};

exchangeRates = fallbackRates;
updateStats();
displayWorldCurrencies();
convertCurrency();
}

// Update alert status
function updateAlert(success, cached = false) {
if (success) {
liveAlert.innerHTML = cached ?
`✅ Using Cached Rates | Last updated: ${new Date(lastUpdated * 1000 || Date.now()).toLocaleString()}` :
`✅ Live Rates Active | Updated: ${new Date().toLocaleTimeString()}`;
liveAlert.className = “alert live”;
} else {
liveAlert.innerHTML = `⚠️ Using Fallback Rates | Live data unavailable`;
liveAlert.className = “alert warning”;
}
}

// Filter and display world currencies
function displayWorldCurrencies() {
worldGrid.innerHTML = ”;

// Remove loading indicator
if (loadingGrid) {
loadingGrid.style.display = ‘none’;
}

// Filter by region
let filtered = worldCurrencies;
if (currentRegion !== “all”) {
filtered = filtered.filter(currency => currency.region === currentRegion);
}

// Filter by search term
if (searchTerm) {
const term = searchTerm.toLowerCase();
filtered = filtered.filter(currency =>
currency.country.toLowerCase().includes(term) ||
currency.code.toLowerCase().includes(term) ||
currency.name.toLowerCase().includes(term)
);
}

// Sort by country name
filtered.sort((a, b) => a.country.localeCompare(b.country));

// Display currencies
filtered.forEach(currency => {
if (currency.code !== baseCurrency) {
const rate = exchangeRates[currency.code] || 1;

const worldItem = document.createElement(‘div’);
worldItem.className = ‘world-item’;

worldItem.innerHTML = `

${currency.country} Flag
${currency.code}
${currency.country}
${currency.name}
${formatRate(parseFloat(rate))}

`;

// Make clickable to set as target
worldItem.addEventListener(‘click’, () => {
targetCurrencySelect.value = currency.code;
targetCurrency = currency.code;
updateFlags();
convertCurrency();

// Highlight clicked item
worldItem.style.background = ‘linear-gradient(135deg, #e8f5e9, #c8e6c9)’;
setTimeout(() => {
worldItem.style.background = ‘white’;
}, 500);
});

worldGrid.appendChild(worldItem);
}
});

// Update count
const uniqueCurrencies = […new Set(filtered.map(c => c.code))];
document.querySelector(‘.grid-title’).innerHTML = `
🌐 Live Currencies (${filtered.length} Countries, ${uniqueCurrencies.length} Currencies)
`;
}

// Initialize everything
async function initialize() {
// Populate selects
populateCurrencySelects();

// Update flags
updateFlags();

// Update time
updateTime();

// Update time every second
setInterval(updateTime, 1000);

// Fetch live rates
await fetchLiveRates();

// Event listeners
baseCurrencySelect.addEventListener(‘change’, function() {
baseCurrency = this.value;
updateFlags();
convertCurrency();
displayWorldCurrencies();
});

targetCurrencySelect.addEventListener(‘change’, function() {
targetCurrency = this.value;
updateFlags();
convertCurrency();
});

convertBtn.addEventListener(‘click’, convertCurrency);
amountInput.addEventListener(‘input’, convertCurrency);

// Search functionality
searchInput.addEventListener(‘input’, function() {
searchTerm = this.value;
displayWorldCurrencies();
});

// Region filter functionality
regionFilters.addEventListener(‘click’, function(e) {
if (e.target.classList.contains(‘region-btn’)) {
// Remove active class from all buttons
document.querySelectorAll(‘.region-btn’).forEach(btn => {
btn.classList.remove(‘active’);
});

// Add active class to clicked button
e.target.classList.add(‘active’);

// Update current region
currentRegion = e.target.dataset.region;
displayWorldCurrencies();
}
});

// Update rates every 5 minutes
setInterval(fetchLiveRates, 300000); // 5 minutes

// Also update every hour
setInterval(fetchLiveRates, 3600000); // 1 hour
}

// Start when page loads
document.addEventListener(‘DOMContentLoaded’, initialize);

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *