This calculator allows you to convert an amount from one currency to another using historical exchange rates. To use it, enter the amount you wish to convert, select the original currency, the target currency, and the date for which you want to retrieve the exchange rate.
function calculateExchangeRate() {
var amount = parseFloat(document.getElementById("amount").value);
var fromCurrency = document.getElementById("fromCurrency").value;
var toCurrency = document.getElementById("toCurrency").value;
var conversionDate = document.getElementById("conversionDate").value;
if (isNaN(amount) || amount <= 0) {
document.getElementById("result").textContent = "Please enter a valid amount greater than zero.";
return;
}
// Placeholder for fetching historical exchange rate data.
// In a real-world application, you would use an API (e.g., from a financial data provider)
// to get the actual historical exchange rate for the specified date and currencies.
// For this example, we'll use hardcoded dummy data for demonstration purposes.
var historicalRates = {
"2023-01-01": {
"USD": {"EUR": 0.94, "GBP": 0.81, "JPY": 130.50, "CAD": 1.35},
"EUR": {"USD": 1.06, "GBP": 0.86, "JPY": 138.80, "CAD": 1.43},
"GBP": {"USD": 1.23, "EUR": 1.16, "JPY": 161.10, "CAD": 1.66},
"JPY": {"USD": 0.0077, "EUR": 0.0072, "GBP": 0.0062, "CAD": 0.0081},
"CAD": {"USD": 0.74, "EUR": 0.70, "GBP": 0.60, "JPY": 123.10}
},
"2024-01-01": {
"USD": {"EUR": 0.91, "GBP": 0.79, "JPY": 142.70, "CAD": 1.34},
"EUR": {"USD": 1.10, "GBP": 0.87, "JPY": 156.80, "CAD": 1.47},
"GBP": {"USD": 1.26, "EUR": 1.15, "JPY": 180.00, "CAD": 1.70},
"JPY": {"USD": 0.0070, "EUR": 0.0064, "GBP": 0.0056, "CAD": 0.0075},
"CAD": {"USD": 0.75, "EUR": 0.68, "GBP": 0.59, "JPY": 134.00}
}
// Add more dates and rates as needed for more comprehensive testing
};
var ratesForDate = historicalRates[conversionDate];
if (!ratesForDate) {
document.getElementById("result").textContent = "Historical data not available for the selected date. Please choose another date.";
return;
}
var rate = 0;
if (fromCurrency === toCurrency) {
rate = 1;
} else if (ratesForDate[fromCurrency] && ratesForDate[fromCurrency][toCurrency]) {
rate = ratesForDate[fromCurrency][toCurrency];
} else if (ratesForDate[toCurrency] && ratesForDate[toCurrency][fromCurrency]) {
// If direct rate isn't available, use the inverse of the opposite rate
rate = 1 / ratesForDate[toCurrency][fromCurrency];
} else {
document.getElementById("result").textContent = "Exchange rate data not found for the selected currencies on this date.";
return;
}
var convertedAmount = amount * rate;
document.getElementById("result").textContent = amount + " " + fromCurrency + " on " + conversionDate + " is approximately " + convertedAmount.toFixed(2) + " " + toCurrency;
}