jQuery函数用于设置数字的逗号和十进制格式

jQuery function to to format number with commas and decimal

本文关键字:十进制 格式 函数 用于 设置 数字 jQuery      更新时间:2023-09-26

我使用以下函数将数字格式化为用户类型。它会每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