2

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.

9
  • What if the user pastes in a value? Things to think about. Commented Apr 15, 2014 at 15:16
  • it works like that already, check fiddle updated. Commented Apr 15, 2014 at 15:19
  • Paste without keyboard. Also it is basically impossible to edit the number if you type it wrong. 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. Commented Apr 15, 2014 at 15:36

2 Answers 2

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/

1
  • It works, even if I insert more decimals. Thanks Commented Jun 30, 2021 at 9:35
10

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(".");
}
1
  • It works, even if I insert more decimals. Thanks Commented Jun 30, 2021 at 9:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.