Intl.NumberFormat 从动态区域设置获取货币代码?

问题描述 投票:0回答:1

我正在努力寻找一种从我的区域设置获取 Intl.NumberFormat 的货币代码的好方法。

我们可以让用户随时更改区域设置。我需要一种方法来根据所选区域设置检索货币代码,以便我可以适当地格式化。

let chosenLocale = appSettings.LocaleKey; //Could be anything user chooses en-US, ja-JP, etc..

// THIS DOES NOT EXIST, DOES ANY SUCH MAPPING, LOOKUP, OR LIST EXIST?
let currencyBasedOnLocale = GetCurrencyCodeFromLocale(chosenLocale); 

// WOULD BE COOL IF THERE WAS THIS FOR ALL KNOWN CURRENCIES:
// var localeCurrencyLookup = { "en-US": "USD", "ru-RU" : "RUB", "en-GB" : "GBP", etc... }
// THEN I COULD DO THIS:
// let currencyBasedOnLocale = localeCurrencyLookup[chosenLocale] || "USD"; 

var formatter = new Intl.NumberFormat(chosenLocale, {
    style: 'currency',
    currency: currencyBasedOnLocale
});
return formatter.format(value);

那么有谁知道是否存在这种区域设置到货币代码的映射?或者有其他方法可以根据区域设置找到货币代码吗?我觉得这是一个巨大的网站,没有区域设置到货币映射。也许大多数网站只支持少数区域设置,让开发人员手动解决。我不介意输入 json 查找映射对象,但我什至不知道去哪里查看哪些语言环境映射到哪种货币代码。

javascript mapping locale currency currency-formatting
1个回答
0
投票

来自我的vue:

import { formatAmount } from 'Composables/Utils/currency'
console.log(formatAmount(15008.36, 'en-US', 'USD'))

来自我的ts

export const formatAmount = (amount:number, getLocale:string, getCurrency:string) => {
  const locale = getLocale
  const currency = getCurrency

  const formats = new Intl.NumberFormat(locale, {
    style: 'currency',
    currency,
    maximumFractionDigits: 2
  })

  return formats.format(amount)
}

结果

$15,008.36

在 Intl.NumberFormat 的第一个参数中使用 undefined 来使用系统区域设置(用户的区域设置)。

© www.soinside.com 2019 - 2024. All rights reserved.