Search code examples
javascriptstringnumberskeyup

thousand and decimal separate in key up event


I used below code to thousand and decimal separate in key up event. But after entering 15 digits value gets 0. what will be the reason ??

<script>
var myinput = document.getElementById('myinput');

myinput.addEventListener('keyup', function() {
  var val = this.value;
  val = val.replace(/[^0-9\.]/g,'');
  
  if(val != "") {
    valArr = val.split('.');
    valArr[0] = (parseInt(valArr[0],10)).toLocaleString();
    val = valArr.join('.');
  }
  
  this.value = val;
});

</script>
<input id="myinput" type="text'>


Solution

  • Problem:

    The problem here is that you reached the maximum possible value for Number on parseInt() when it tries to parse the input string value, check the Number.MAX_SAFE_INTEGER MDN Reference for further details.

    So all the extra digits you enter, when the number exceeds the Number.MAX_SAFE_INTEGER, will be ignored and transformed to 0. Please check Working with large integers in JavaScript tutorial for more explanation and examples.

    So, you can't treat a large number value as a Number in Javsacript because there's a Maximum possible value limit, you need to treat it as a string, so it can exceed this max value.

    Solution:

    The solution here is to treat this number as a string and use Regex and .replace() method to change its format.

    Here's a solution that I wrote before and that I always use to format numbers, it will solve your problem:

    var formatNumber = function(input, fractionSeparator, thousandsSeparator, fractionSize) {
    
      fractionSeparator = fractionSeparator || '.';
      thousandsSeparator = thousandsSeparator || ',';
      fractionSize = fractionSize || 3;
      var output = '',
        parts = [];
    
      input = input.toString();
      parts = input.split(".");
      output = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSeparator).trim();
      if (parts.length > 1) {
        output += fractionSeparator;
        output += parts[1].substring(0, fractionSize);
      }
      return output;
    };
    

    Demo:

    This is a working Fiddle with your original code.