Q:

Add thousand separator with 2 decimals place using jQuery

Currently, what I have is this using jQuery. 
Code.html
<input type="text" class="inputnumber" name="inputnumber" value="" placeholder="">

Code.js 
  $('input.inputnumber').keyup(function(event) {
    if(event.which >= 37 && event.which <= 40) return;
    $(this).val(function(index, value) {
      return value
      .replace(/\D/g, "")
      .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
      ;
    });
  });

Right now, I can only add number with thousand separator in my input field.
1,000,000

But my goal is to allow user to add thousand separator with 2 decimals like below. 
1,000,000.00 

How can I achieve it in my code ? Appreciate if someone can help me to solve this problem.
Thanks in advance.

A:

Your current
/\D/g, ""

will remove all non-digit characters, including periods. Use a negated character set instead, removing everything but digits and periods, and it'll work as intended:
/[^\d.]/

To also restrict to 2 decimal places, add this as well:
.replace(/\.(\d{2})\d+/, '.$1')

which will replace (decimal followed by 2+ digits) with (decimal followed by 2 digits):

$('input.inputnumber').keyup(function(event) {
  if (event.which >= 37 && event.which <= 40) return;
  $(this).val(function(index, value) {
    return value
      // Keep only digits and decimal points:
      .replace(/[^\d.]/g, "")
      // Remove duplicated decimal point, if one exists:
      .replace(/^(\d*\.)(.*)\.(.*)$/, '$1$2$3')
      // Keep only two digits past the decimal point:
      .replace(/\.(\d{2})\d+/, '.$1')
      // Add thousands separators:
      .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="inputnumber" name="inputnumber" value="1,000,000.00">

To allow -s at the beginning as well, put - inside the character set in initial .replace, and also match and remove -s not at the beginning of the string with (?!^)-:

$('input.inputnumber').keyup(function(event) {
  if (event.which >= 37 && event.which <= 40) return;
  $(this).val(function(index, value) {
    return value
      // Keep only digits, decimal points, and dashes at the start of the string:
      .replace(/[^\d.-]|(?!^)-/g, "")
      // Remove duplicated decimal points, if they exist:
      .replace(/^([^.]*\.)(.*$)/, (_, g1, g2) => g1 + g2.replace(/\./g, ''))
      // Keep only two digits past the decimal point:
      .replace(/\.(\d{2})\d+/, '.$1')
      // Add thousands separators:
      .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="inputnumber" name="inputnumber" value="1,000,000.00">

