js金额汇率转换

[
  { 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;
  },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值