gpt4 book ai didi

node.js - Intl.NumberFormat 在 Node 和浏览器中的不同行为

转载 作者:搜寻专家 更新时间:2023-10-31 23:01:15 25 4
gpt4 key购买 nike

如果我在浏览器和 Node 中运行这段代码,我会得到两个不同的结果:

const moneyFormatter = new Intl.NumberFormat('it-IT', {
style: 'currency',
currency: 'EUR',
minimumFractionDigits: 2
});

moneyFormatter.format(1);

浏览器:1,00 €

Node :€1.00

最佳答案

ICU 和 Node

这个问题是由于缺少ICU引起的默认 Node 构建中的数据。

Nodejs docs explain it这个功能很好:

Node.js (and its underlying V8 engine) uses ICU to implement these features in native C/C++ code. However, some of them require a very large ICU data file in order to support all locales of the world.

及其在默认 Node 构建中的局限性:

Because it is expected that most Node.js users will make use of only a small portion of ICU functionality, only a subset of the full ICU data set is provided by Node.js by default.

所以:

Several options are provided for customizing and expanding the ICU data set either when building or running Node.js.

快速解决方案

安装 full-icu npm 包就大功告成了:每个语言环境都将被安装并可以使用。只需使用指向 icu 数据集安装的专用环境变量启动您的应用程序:

NODE_ICU_DATA=node_modules/full-icu node YOURAPP.js

或者,使用替代 Node 选项:

node --icu-data-dir=node_modules/full-icu YOURAPP.js

此解决方案的唯一缺点是完整 icu 数据集所需的空间:~27Mb。

速度慢但空间优化的解决方案

从源代码编译 Node bundling it with only a specific ICU .

检查可用的语言环境

Intl.NumberFormat.supportedLocalesOf('it')

如果不支持语言环境,它返回一个空数组[]。如果支持语言环境,它会返回一个带有语言环境 ID ['it'] 的数组。

关于node.js - Intl.NumberFormat 在 Node 和浏览器中的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55183776/

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