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

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,所以请在此处保留此问题。

最佳答案

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

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"

09-11 19:30