首页 > 解决方案 > 根据反应应用程序中的 API 字段转换货币

问题描述

我在 React 中开发了一个小部件,其中显示了一些成本值,并且货币基于来自 API 的字段。所以有一个实际成本 = 1070。所以当单位是美元时,我们将显示1.1k$

这是通过已经编写的函数完成的

export const formatCurrency = (
  value: number,
  symbol: string = 'USD',
  locale: string = 'en-US'
) => {
  return Formatters(locale).number.currency(symbol)(value);
};

export const getSymbolFromCurrency = (currencyCode: string) => {
  const currencySymbolMap: Record<string, string> = {
    USD: '$', // US Dollar
    EUR: '€', // Euro
    CRC: '₡', // Costa Rican Colón
    GBP: '£', // British Pound Sterling
    INR: '₹' // Indian Rupee
  };
  if (typeof currencyCode !== 'string') {
    return undefined;
  }
  const code = currencyCode.toUpperCase();
  return currencySymbolMap[code];
};

此函数能够基于单位来转换符号,例如“INR”“GBP”,但值没有得到转换

我需要在 formatCurrency 中添加什么语言环境,以便它自动更改值,因为该函数需要两个参数 {formatCurrency(actualCost, costCurrency)}

在此处输入图像描述

标签: javascriptreactjs

解决方案


目前还不清楚你在追求什么,但为了表示1070$1.1k,你可以使用Intl.NumberFormat的紧凑符号选项。

您通常也不需要提供自己的货币符号,只需提供货币代码即可。

// I've tried to match `Formatters` to the way you seem to expect to use it
const Formatters = locale => ({
  number: {
    currency: currency => {
      const formatter = new Intl.NumberFormat(locale, {
        style: "currency",
        notation: "compact", // 
        currency
      })
      return value => formatter.format(value)
    }
  }
})

// copied as plain JS from your question
const formatCurrency = (
  value,
  symbol = 'USD',
  locale = 'en-US'
) => Formatters(locale).number.currency(symbol)(value)

for (let [ locale, currency ] of [["en-US","USD"],["fr-FR","EUR"],["es-CR","CRC"],["en-GB","GBP"],["hi-IN","INR"]]) {
  console.log(`${currency} (${locale}):`,
    formatCurrency(1070, currency, locale))
}
.as-console-wrapper { max-height: 100% !important; }


推荐阅读