[
{ code: "USD", name: "美元" },
{ code: "EUR", name: "欧元" },
{ code: "JPY", name: "日元" },
{ code: "GBP", name: "英镑" },
{ code: "CAD", name: "加元" },
{ code: "AUD", name: "澳元" },
{ code: "HKD", name: "港元" },
{ code: "CHF", name: "瑞郎" },
{ code: "SGD", name: "新元" },
{ code: "NZD", name: "新西兰元" },
{ code: "CNY", name: "人民币" },
]
/**
* 将货币金额转换为目标货币金额
* @param {number} amount - 货币金额
* @param {string} fromCurrency - 源货币种类,例如:USD
* @param {string} toCurrency - 目标货币种类,例如:CNY
* @return {Promise<number>} 返回对应的目标货币金额
*/
async convertCurrency(amount, fromCurrency, toCurrency) {
// 定义汇率 API 地址
const api = `https://api.exchangerate-api.com/v4/latest/${fromCurrency}`;
// 调用 API,得到汇率数据,并转换为 JSON 格式
const response = await fetch(api);
const data = await response.json();
// 从汇率数据中获取源货币对目标货币的汇率
const exchangeRate = data.rates[toCurrency];
// 计算目标货币金额,保留两位小数
const result = (amount * exchangeRate).toFixed(2);
// 返回目标货币金额
return result;
},
js金额汇率转换
最新推荐文章于 2024-08-27 13:16:34 发布