【问题标题】:Javascript regex: format moneyJavascript 正则表达式:格式化货币
【发布时间】:2017-06-02 08:00:56
【问题描述】:

我使用以下函数来格式化数字:

function formatNumber(value, precision) {
    if (Number.isFinite(value)) {
        // Source: kalisjoshua's comment to VisioN's answer in the following stackoverflow question:
        // http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript
        return value.toFixed(precision || 0).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,")
    } else {
        return ""
    }
}

除一种情况外,上述工作:

1130.000200 becomes 1,130.000,200

但我需要

1130.000200 become 1,130.000200

似乎我需要在?<! 后面进行否定的查找,即匹配一个不以点开头的数字,但是如何匹配?

编辑:正如this question 中的回答,Number.prototype.toLocaleString() 是较新浏览器的一个很好的解决方案。我需要支持 IE10,所以把这个问题留在这里吧。

【问题讨论】:

标签: javascript regex


【解决方案1】:

您可以使用这个简单的函数来格式化十进制数:

function fmt(num) {
   // split into two; integer and fraction part
   var arr = num.match(/^(\d+)((?:\.\d+)?)$/);

   // format integer part and append fraction part
   return arr[1].replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') + arr[2];
}

var s1 = fmt('1130.000200')
//=> "1,130.000200"

var s2 = fmt('1130000200')
//=> "1,130,000,200"

【讨论】:

    【解决方案2】:

    只需在.Match 之后删除?。更新的模式是/(\d)(?=(\d{3})+(?:\.\d+)$)/g,

    ?量词 - 匹配 0 次和 1 次,次数为 可能,根据需要回馈

    Demo regex and explanation

    console.log('1130.000200'.replace(/(\d)(?=(\d{3})+(?:\.\d+)$)/g, "$1,"))

    【讨论】:

    • 你在我给出的例子中是对的,但它不会匹配整数。
    【解决方案3】:

    让它与下面的代码一起工作。

    关键是匹配变量d的小数点。如果不匹配,请不要替换。

    function formatNumber(value, precision) {
        var regex = /(\d)(?=(\d{3})+(?:(\.)\d+)?$)/g;
        return (+value).toFixed(precision || 0).replace(regex, function(a, b, c, d) {
                return d ? b+',' : b;
            });
    }
    
    console.log(formatNumber(1130.000200, 6));
    console.log(formatNumber(1130, 6));

    来自 regex101 的示例,您会看到小数点匹配到第 3 组。https://regex101.com/r/qxriNx/1

    【讨论】:

    • 获得一次赞成票,一次反对票。请发表评论,以便我改进答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    • 2017-12-29
    • 1970-01-01
    • 2010-10-23
    相关资源
    最近更新 更多