javascript - 根据反应应用程序中的 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)}
解决方案
目前还不清楚你在追求什么,但为了表示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; }
推荐阅读
- php - 如何在环境之间分隔 PHP $_SESSION 变量?
- swift - 静态变量的 Self.XXX 是什么意思
- javascript - Selenium 不检索动态生成的 html
- reactjs - 如何在下拉列表中显示数据中的选定选项?
- angular - Angular 7 应用程序的 CROSS 起源问题
- java - excel中一列的最后一行使用POI for selenium-java
- linux - 操作给定命令的系统时间
- python - 为什么在 Python 中创建命名元组对象后无法读取“类型名”
- hibernate - 引起:java.lang.IllegalArgumentException:org.hibernate.hql.internal.ast.QuerySyntaxException:意外令牌:近线
- sql - 当使用触发器在 Student 表中插入 1 行时,我需要在 Student_Fee 表中创建 3 行