javascript - jQuery 函数用逗号和小数格式化数字

标签 javascript jquery regex

我正在使用以下函数在用户键入时格式化数字。它将每 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

Example

关于javascript - jQuery 函数用逗号和小数格式化数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14075014/

相关文章:

javascript - JavaScript 中计算字符串中数字出现的次数

c# - C# 中的正则表达式问题返回匹配为真

javascript - 在新窗口中打开页面上的 div,同时保持通过 websocket 更新它的能力

javascript - 我需要应用的正确过渡结束(或动画结束)是什么?

javascript - jquery:仅保留单个选定的div

python - 使用Python正则表达式忽略字符串中的 `:`

MySql 模式匹配

javascript - 在 JavaScript 中,在声明新键 :value pairs of the object? 时引用对象的变量名与使用 `this` 之间有区别吗

javascript - 动态改变<script>标签src

javascript - React Native - 意外的标识符