Intl.NumberFormat不会转换为pt-BR语言环境

时间:2020-01-31 21:17:35

标签: javascript node.js

我有以下代码示例:

const formCurrency = new Intl.NumberFormat('pt-BR', {
    style: 'currency',
    currency: 'BRL',
    minimumFractionDigits: 2
})

如果输入是:

var money = 1000.50

formCurrency.format(money)

预期输出为:R$ 1.000,50, 但是它却给出了:R$ 1,000.50

有人知道如何使用,来更改.或使用Intl来进行其他更改吗?

我已经尝试将语言环境更改为de-DE,但是效果不佳。对于其他styleR$会发生变化,但标点符号的其余部分不会发生变化。

5 个答案:

答案 0 :(得分:1)

感谢阿尔瓦罗(Alvaro),我找到了一种方法。根据MDN和Node文档本身,Node.js仅支持美国语言环境。因此,要使其正常工作,我需要:

  • 使用full-icu安装npm i full-icu软件包
  • 安装后进行一次npm-rebuild
  • package.json文件中添加以下代码:

    "scripts": { "start":"node --icu-data-dir=node_modules\\full-icu YOURAPP.js" }

  • 使用npm start
  • 运行节点应用程序

现在,它会获得正确的语言环境并也执行正确的标点符号。

答案 1 :(得分:1)

在生产中采取的步骤(类似于@Mael 的 answer,但几乎没有变化)

1- 在 package.json 中添加依赖项(在本地运行 npm i full-icu 在提交之前执行此操作);

2- 在节点运行您的应用程序之前添加到 icu-data-dir 的路径,然后编辑您的 start 脚本:

"start": "node --icu-data-dir=./node_modules/full-icu yourEntryFile.js"

只有这些步骤对我有用。可以对其他人有所帮助。

答案 2 :(得分:0)

嗯,这不是最佳解决方案,但应该可以解决问题

let result = formCurrency.format(money);
result = result.split('.');
result[0] = result[0].replace(',' , '.');
result = result.join(',');

我试图用正则表达式来做,但是找不到一个好方法。

答案 3 :(得分:0)

我使用语言环境“id”(印度尼西亚),它对我有用。

var number = '1555666.99';
console.log(new Intl.NumberFormat('id').format(number))
result: 1.555.666,99

enter image description here

答案 4 :(得分:0)

使用这个...

function convertMoneyValue(number,element){
    number = parseFloat((number/100)).toFixed(2);
    element.value = (new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(number));
}
相关问题