簡體   English   中英

Javascript正則表達式:格式貨幣

[英]Javascript regex: format money

我使用以下函數來格式化數字:

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

看來我需要負面的回望?<! ,即匹配一個不帶點號的數字,但是如何匹配?

編輯:正如在此問題中回答,Number.prototype.toLocaleString()是較新的瀏覽器的一個很好的解決方案。 我需要支持IE10,所以請在此處保留此問題。

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

量詞-匹配零到一遍,盡可能多地匹配,並根據需要返回

演示正則表達式和說明

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

使它與下面的代碼一起使用。

關鍵是匹配變量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

您可以使用此簡單函數來格式化您的十進制數字:

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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM