javascript - 无法在nodejs中使用toLocaleString

标签 javascript node.js express

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

这是格式库

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/

相关文章:

javascript - 仅在Express中针对某些路由运行中间件的模式

node.js - MEAN 堆栈安装给出 304 和 404s

node.js - 在 NodeJS localhost 中设置时区以反射(reflect)生产环境

javascript - 帮助 JQuery 回调

javascript - 如何在 JSDoc(或 TypeScript?)中记录函数自定义类型并引用它们以便 VSCode IntelliSense 工作

node.js - 使用 --watch 时,node-sass cli 在初始运行时未编译

node.js - Node JS 和 Sequelize 错误 : Cannot set headers after they are sent to the client

javascript - 我现在可以得到 future 未处理的 promise 拒绝行为吗?

javascript - 将代码包装在一个函数中。菜鸟在这里

javascript - React - 将搜索添加到表中,正确的方法?