gpt4 book ai didi

javascript - 无法在nodejs中使用toLocaleString

转载 作者:行者123 更新时间:2023-12-03 00:32:47 25 4
gpt4 key购买 nike

我创建了一个实用程序库来格式化数字。

这是格式库

module.exports = {
format: function (number) {
let value = number.toString()
let teste = value.slice(0, -2) + '.' + value.slice(-2)
let newvalue = Number(teste)
return newvalue.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })
}
}

在我的文件中我将其导入并使用:

var format = require('../utils/format').format
let number = format(31231)

但它没有返回正确的格式R$2.312,31返回R$2,312.31

如果我在 JsFiddle 中运行,它会按预期工作...不知道会出现什么问题

最佳答案

正如评论中提到的,它看起来像 bug in node - 你可以更正

const reformat = s => s.replace(/[,.]/g, x => ({'.':',', ',':'.'})[x]);

console.log(reformat('R$2,312.31'))

您可能还想在替换件上放置一个防护装置:

s => /\.\d{2}$/.test(s) ? s.replace(/[,.]/g, x => ({'.':',', ',':'.'})[x]) : s

在你的库中使用它,如下所示:

module.exports = {
format: function (number) {
let value = number.toString()
let teste = value.slice(0, -2) + '.' + value.slice(-2)
let newvalue = Number(teste)
const reformat = s => /\.\d{2}$/.test(s) ? s.replace(/[,.]/g, x => ({'.':',', ',':'.'})[x]) : s
return reformat(newvalue.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }))
}
}

关于javascript - 无法在nodejs中使用toLocaleString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53786147/

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