javascript Jquery在输入时添加逗号以输入带小数的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23087867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:18:40  来源:igfitidea点击:

Jquery adding commas to input number with decimals while typing

javascriptjqueryhtmlnumbersdecimal

提问by Hard Fitness

I am trying to add commas to an input text that allows a number while typing it. But should also allow decimals. Here is my code for the numbers only, just can't figure out the decimal thing.

我试图在输入文本中添加逗号,以便在输入时输入数字。但也应该允许小数。这是我的数字代码,只是无法弄清楚小数点。

$('input.number').keyup(function(event) {

  // skip for arrow keys
  if(event.which >= 37 && event.which <= 40){
   event.preventDefault();
  }

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

If anyone has a solution that would be great thx.

如果有人有一个很好的解决方案,那就太好了。

Fiddle: http://jsfiddle.net/yWTLk/348/

小提琴:http: //jsfiddle.net/yWTLk/348/

UPDATE: Some good comments, but perhaps can anyone think of a way to have input text field which its editable and at same time formats your number with commas and respects decimals. Something tells me its nearly impossible to do this but let's see if anyone can think of a solution.

更新:一些好的评论,但也许任何人都可以想出一种方法来输入文本字段,该字段可编辑,同时用逗号格式化您的数字并尊重小数。有人告诉我几乎不可能做到这一点,但让我们看看是否有人能想到解决方案。

And the reason why its good to have auto format while typing is because if you are entering a very large number you might get lost while doing it. For example:

打字时自动格式化的好处是因为如果你输入一个非常大的数字,你可能会在输入时迷路。例如:

  10000000000000000000000000000000000000000000

That would be a nightmare to enter correctly, hence auto format would tell you if you are missing or not a zero. On the other hand validating it afterwards will show u the error and perhaps yes you can correct it but its an extra step.

正确输入将是一场噩梦,因此自动格式会告诉您是否缺少零。另一方面,事后验证它会告诉你错误,也许是的,你可以纠正它,但它是一个额外的步骤。

回答by hyperdrive

Could do this, but what I would do instead is show the comma separated number elsewhere besides the input field.

可以这样做,但我要做的是在输入字段之外的其他地方显示逗号分隔的数字。

$('input.number').keyup(function(event) {

  // skip for arrow keys
  if(event.which >= 37 && event.which <= 40){
   event.preventDefault();
  }

  $(this).val(function(index, value) {
      value = value.replace(/,/g,''); // remove commas from existing input
      return numberWithCommas(value); // add commas back in
  });
});

function numberWithCommas(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}

http://jsfiddle.net/jpAmE/

http://jsfiddle.net/jpAmE/

回答by TriniBoy

I think this might do what you are looking for. Assumptions:

我认为这可能会做你正在寻找的。假设:

  1. Users are only allowed to enter one decimal point.
  2. no formatting is allowed after the decimal point, i.e. commas.
  1. 用户只能输入一位小数。
  2. 小数点后不允许有格式,即逗号。

Fiddle

小提琴

$('input.number').keyup(function (event) {
    // skip for arrow keys
    if (event.which >= 37 && event.which <= 40) {
        event.preventDefault();
    }

    var currentVal = $(this).val();
    var testDecimal = testDecimals(currentVal);
    if (testDecimal.length > 1) {
        console.log("You cannot enter more than one decimal point");
        currentVal = currentVal.slice(0, -1);
    }
    $(this).val(replaceCommas(currentVal));
});

function testDecimals(currentVal) {
    var count;
    currentVal.match(/\./g) === null ? count = 0 : count = currentVal.match(/\./g);
    return count;
}

function replaceCommas(yourNumber) {
    var components = yourNumber.toString().split(".");
    if (components.length === 1)
        components[0] = yourNumber;
    components[0] = components[0].replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    if (components.length === 2)
        components[1] = components[1].replace(/\D/g, "");
    return components.join(".");
}