jquery - 使用 jQuery 添加小数点后两位的千位分隔符

标签 jquery regex

目前,我所拥有的是使用 jQuery 的。

代码.html

<input type="text" class="inputnumber" name="inputnumber" value="" placeholder="">

Code.js

  $('input.inputnumber').keyup(function(event) {
    if(event.which >= 37 && event.which <= 40) return;
    $(this).val(function(index, value) {
      return value
      .replace(/\D/g, "")
      .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
      ;
    });
  });

现在,我只能在输入字段中添加带有千位分隔符的数字。

1,000,000

但我的目标是允许用户添加带有 2 位小数的千位分隔符,如下所示。

1,000,000.00 

如何在我的代码中实现它?如果有人能帮助我解决这个问题,我将不胜感激。

提前致谢。

最佳答案

您当前的

/\D/g, ""

将删除所有非数字字符,包括句点。使用否定字符集,删除除数字和句点之外的所有内容,它将按预期工作:

/[^\d.]/

要限制为小数点后两位,请添加以下内容:

.replace(/\.(\d{2})\d+/, '.$1')

将(小数后跟 2 位以上数字)替换为(小数后跟 2 位数字):

$('input.inputnumber').keyup(function(event) {
  if (event.which >= 37 && event.which <= 40) return;
  $(this).val(function(index, value) {
    return value
      // Keep only digits and decimal points:
      .replace(/[^\d.]/g, "")
      // Remove duplicated decimal point, if one exists:
      .replace(/^(\d*\.)(.*)\.(.*)$/, '$1$2$3')
      // Keep only two digits past the decimal point:
      .replace(/\.(\d{2})\d+/, '.$1')
      // Add thousands separators:
      .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="inputnumber" name="inputnumber" value="1,000,000.00">

要在开头也允许 -,请将 - 放入初始 .replace 的字符集中,并匹配和删除- 不在字符串的开头,(?!^)-:

$('input.inputnumber').keyup(function(event) {
  if (event.which >= 37 && event.which <= 40) return;
  $(this).val(function(index, value) {
    return value
      // Keep only digits, decimal points, and dashes at the start of the string:
      .replace(/[^\d.-]|(?!^)-/g, "")
      // Remove duplicated decimal points, if they exist:
      .replace(/^([^.]*\.)(.*$)/, (_, g1, g2) => g1 + g2.replace(/\./g, ''))
      // Keep only two digits past the decimal point:
      .replace(/\.(\d{2})\d+/, '.$1')
      // Add thousands separators:
      .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="inputnumber" name="inputnumber" value="1,000,000.00">

关于jquery - 使用 jQuery 添加小数点后两位的千位分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52196132/

相关文章:

按下后退按钮时的 Jquery

c - flex 无法识别字符范围

javascript - Jquery ReplaceWith 保持 onclick

javascript - 如何将 javascript 添加到 html 文档的头部以监听尚未添加到 DOM 的元素的点击?

php - 如何修复 "Uncaught SyntaxError: Unexpected token _ in JSON at position . . . "

javascript - 正则表达式获取 API 表单 URL 的版本

javascript - 从文件名中删除非法字符但保留空格

c# - 如何检测非英文输入?

java - RegEx 仅匹配不以单引号开头或结尾的数字

javascript - 窗口莫名检测到滚动