gpt4 book ai didi

javascript - Intl.NumberFormat 中的多个区域设置?

转载 作者:行者123 更新时间:2023-12-01 02:27:39 24 4
gpt4 key购买 nike

我必须处理三种不同的货币:美元、乌克兰格里夫纳和欧元。为了使用 Intl.NumberFormat 正确显示它们中的每一个,我必须为每个使用不同的区域设置:

const _ = { style: "currency" };

// notice different locales
new Intl.NumberFormat("en", { ..._, currency: "USD" }).format(15); // $15.00
new Intl.NumberFormat("uk", { ..._, currency: "UAH" }).format(15); // 15,00 грн.
new Intl.NumberFormat("de", { ..._, currency: "EUR" }).format(15); // 15,00 €

因此,为了使其发挥作用,我必须为每种货币提供不同的区域设置:

const currency = {
code: "USD", // "USD" | "UAH" | "EUR"
rate: 1, // arbitrary
locale: "en", // "en" | "uk" | "de"
}

new Intl.NumberFormat(currency.locale, { ..._, currency: currency.code }).format(15);

我发现这种方法不太优雅:模型应该对 View 一无所知。
但还有更好的吗?

也许可以使用多个区域设置,如下所示:

const LOCALES = ["en", "uk", "de"];

// ...

new Intl.NumberFormat(LOCALES, { ..._, currency: currency.code }).format(15);

最佳答案

我有点怀疑是否需要真正这样做(多个区域设置)。

想想将会看到此内容的用户。

他们习惯于在一种语言环境中查看事物,并且可能不知道某种货币的“语言环境约定”是什么。

但问题是,货币并不能决定格式。如果我是美国人,那么我预计会看到 12,345.67 美元、12,345.67 欧元和 12,345.67 日元我不熟悉欧洲或日本的惯例。

所以我认为您应该对所有格式使用相同的区域设置(当前用户区域设置)。哎呀,我什至可能不知道“грн”是什么,我宁愿期待类似“12,345.67 乌克兰格里夫纳”或“UAH 12,345.67”的东西,就像大多数货币兑换亭一样。所以这取决于用例。

但是,如果您确实希望格式遵循货币,而不是用户自定义,那么使用不同的格式化程序是唯一的方法。您想要的不是常见的用例,因此没有 API 来支持它。

关于javascript - Intl.NumberFormat 中的多个区域设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48609279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com