使用jQuery/JS在输入时使用1000个分隔符和2个小数位来格式化货币输入?

e4eetjau  于 2023-10-17  发布在  jQuery
关注(0)|答案(3)|浏览(96)

我有一个文本输入,我希望它的格式,而键入一个值,允许2个小数位和1000分隔符。它应该只允许数字。我已经做了以下操作,但它不允许添加小数点。简单地说,它是用于输入产品(货币)的价格。
INPUT = 1234560ABC.5665(应该只允许数字)
预期值= 1,234,560.56(应将小数位数限制为2)
我已经做了以下工作,但不知道如何添加小数值,后面跟着一个“.”,以确保“,”1000分隔符。

<input type="text" id="price" name="price" />

$('#price').keyup(function (event) {
    $(this).val(function (index, value) {
        return '$' + value.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    });
});
jmp7cifd

jmp7cifd1#

我的解决方案使用连续的.replace

  1. .replace(/(?!\.)\D/g, "")删除除.以外的所有非数字字符
  2. .replace(/(?<=\..*)\./g, "")删除除第一个.之外的所有额外的.
  3. .replace(/(?<=\.\d\d).*/g, "")删除小数点后2位的所有内容
  4. .replace(/\B(?=(\d{3})+(?!\d))/g, ",")在适当位置插入逗号
    我已经修改了事件,以将对输入字段的所有更改解释为.on('change click keyup input paste'

片段:

$('#price').on('change click keyup input paste',(function (event) {
    $(this).val(function (index, value) {
        return '$' + value.replace(/(?!\.)\D/g, "")
                          .replace(/(?<=\..*)\./g, "")
                          .replace(/(?<=\.\d\d).*/g, "")
                          .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    });
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="price" name="price" />
gzszwxb4

gzszwxb42#

您可以限制keydown事件中的键而不是keyup,并允许特定键生效,然后格式化keyup事件的输入:

$("#testinput").on("keydown", function(e) {
  var keycode = (event.which) ? event.which : event.keyCode;
  if (e.shiftKey == true || e.ctrlKey == true) return false;
  if ([8, 110, 39, 37, 46].indexOf(keycode) >= 0 || // allow tab, dot, left and right arrows, delete keys
    (keycode == 190 && this.value.indexOf('.') === -1) || // allow dot if not exists in the value
    (keycode == 110 && this.value.indexOf('.') === -1) || // allow dot if not exists in the value
    (keycode >= 48 && keycode <= 57) || // allow numbers
    (keycode >= 96 && keycode <= 105)) { // allow numpad numbers
    // check for the decimals after dot and prevent any digits
    var parts = this.value.split('.');
    if (parts.length > 1 && // has decimals
      parts[1].length >= 2 && // should limit this
      (
        (keycode >= 48 && keycode <= 57) || (keycode >= 96 && keycode <= 105)
      ) // requested key is a digit
    ) {
      return false;
    } else {
      if (keycode == 110) {
        this.value += ".";
        return false;
      }
      return true;
    }
  } else {
    return false;
  }
}).on("keyup", function() {
  var parts = this.value.split('.');
  parts[0] = parts[0].replace(/,/g, '').replace(/^0+/g, '');
  if (parts[0] == "") parts[0] = "0";
  var calculated = parts[0].replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
  if (parts.length >= 2) calculated += "." + parts[1].substring(0, 2);
  this.value = calculated;
  if (this.value == "NaN" || this.value == "") this.value = 0;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="testinput">
ddarikpa

ddarikpa3#

$('#price').on('keyup click change paste input', function (event) {
    $(this).val(function (index, value) {
        if (value != "") {
            //return '$' + value.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            var decimalCount;
            value.match(/\./g) === null ? decimalCount = 0 : decimalCount = value.match(/\./g);

            if (decimalCount.length > 1) {
                value = value.slice(0, -1);
            }

            var components = value.toString().split(".");
            if (components.length === 1)
                components[0] = value;
            components[0] = components[0].replace(/\D/g, '').replace(/\B(?=(\d{3})+(?!\d))/g, ',');
            if (components.length === 2) {
                components[1] = components[1].replace(/\D/g, '').replace(/^\d{3}$/, '');
            }

            if (components.join('.') != '')
                return '$' + components.join('.');
            else
                return '';
        }
    });
});

相关问题