最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery adding commas to input number with decimals while typing - Stack Overflow

programmeradmin2浏览0评论

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: /

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.

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/

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.

Share Improve this question edited Apr 15, 2014 at 15:42 Hard Fitness asked Apr 15, 2014 at 15:15 Hard FitnessHard Fitness 4523 gold badges9 silver badges24 bronze badges 9
  • What if the user pastes in a value? Things to think about. – epascarello Commented Apr 15, 2014 at 15:16
  • it works like that already, check fiddle updated. – Hard Fitness Commented Apr 15, 2014 at 15:19
  • Paste without keyboard. Also it is basically impossible to edit the number if you type it wrong. – epascarello Commented Apr 15, 2014 at 15:30
  • 2 From a user experience point of view, I would highly recommend letting them enter their value and then, if the value is valid, update the format afterwards. Auto-formatting as the user is typing can make for a highly frustrating interface. – talemyn Commented Apr 15, 2014 at 15:30
  • i agree, just need to have it done in real time. Other option is once they click off then they value can be updated. – Hard Fitness Commented Apr 15, 2014 at 15:36
 |  Show 4 more comments

2 Answers 2

Reset to default 12

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/

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.

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(".");
}
发布评论

评论列表(0)

  1. 暂无评论