[英]jQuery function to to format number with commas and decimal
我正在使用以下函數來格式化數字作為用戶類型。 它將每3個數字插入一個逗號。 例: 45696.36
變為45,696.36
。
但是,我遇到了一個問題。 如果小數點后的數字超過3位數,則會開始向它們添加逗號。 例如: 1136.6696
變為1,136.6,696
。
這是我的功能:
$.fn.digits = function(){
return this.each(function() {
$(this).val( $(this).val().replace(/[^0-9.-]/g, '') );
$(this).val( $(this).val().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );
})
}
我如何解決這個問題,以便在小數點后停止逗號? 我正在使用jQuery 1.8。 謝謝!
您可以通過將字符串拆分為'來完成此操作.
'字符然后僅在第一部分執行逗號轉換,如下所示:
function ReplaceNumberWithCommas(yourNumber) {
//Seperates the components of the number
var n= yourNumber.toString().split(".");
//Comma-fies the first part
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return n.join(".");
}
ReplaceNumberWithCommas(1136.6696); //yields 1,136.6696
我使用accounting.js lib:
accounting.format(1136.6696, 4) // 1,136.6696
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.