代码之家  ›  专栏  ›  技术社区  ›  Igor Martins

无法在nodejs中使用ToLocalString

  •  0
  • Igor Martins  · 技术社区  · 7 年前

    我已经创建了一个util库来格式化一个数字。

    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

    如果我像预期的那样在JSFIDLE中运行,我不知道会出什么问题

    1 回复  |  直到 7 年前
        1
  •  1
  •   ic3b3rg    7 年前

    正如评论中提到的,它看起来像一个 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' }))
      }
    }
    
    推荐文章