Convert input value to currency format when user type

I have failed to convert the input value to currency format. I want to automaticly add thousands and decimal separators when the user types the number (5,000.00; 125,000.00).

Here’s my code :

$('input.CurrencyInput').on('blur, focus, keyup',
    function() {
        $(this).val().toLocaleString('en-US', {
            style: 'decimal',
            maximumFractionDigits: 2,
            minimumFractionDigits: 2
        });
    });

Answer

There are a couple of problems with your code:

  1. You’re using comma when binding multiple event handlers to the input box.
  2. You’re not converting the received value to a number before applying toLocaleString on it.
  3. You’re not setting the value of the textbox again after conversion.

Correcting these, here is a working demo. For the sake of simplicity, I’ve removed the other event handlers, except blur, as keyup was causing problems.

$('input.CurrencyInput').on('blur', function() {
  const value = this.value.replace(/,/g, '');
  this.value = parseFloat(value).toLocaleString('en-US', {
    style: 'decimal',
    maximumFractionDigits: 2,
    minimumFractionDigits: 2
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="CurrencyInput">

Leave a Reply

Your email address will not be published. Required fields are marked *