JM-AGMS JM-AGMS - 2 months ago 18
Javascript Question

Currency masking and formatting when entering numbers

This is what I want to do:


Everything I found so far was simply masking currency with two zeros after a decimal point, or a comma for the thousands, which I already know how to do.

I need to be able to keep appending digits in a currency format when users type, starting with 0.00 as the starting point. I need to do this to several inputs. I'm thinking I will need to track all digits entered by the user for each respective input. I'm not even sure how best to approach this. How can I do this?

I put something together for my example but its pretty barebones.

Sale $<input type="text" value=""><br>
Tax $<input type="text" value="">

$(document).on('input',':input',function() {
if (this.value.length === 1) {
this.value = '0.0'+this.value;
}
});


https://jsfiddle.net/apxh4eL2/1/

Answer Source

Thanks to Jitendra Softgrid for pretty much answering my question in the comments. I modified the code to catch more conditions. Below is the final version I used. I hope this helps someone else.

$(document).on('input',':input',function() {
  var v = this.value, dollar = '0', cents = '00';
  if (v.indexOf('.') !== -1) {
    var price = v.split('.');
    dollar = price[0] || '0';
    cents = price[1] || '00';
  }
  if (cents.length === 1) {
    if (dollar) {
      var dollarNumbers = dollar.split('');
      var dollarLength = dollarNumbers.length;
      cents = dollarNumbers[dollarLength-1]+cents;
      dollar = '';
      for (var i = 0; i < dollarLength-1 ; i++) {
        dollar += dollarNumbers[i];
      }
      if (!dollar) {dollar = '0';}
    }
  }
  if (v.length === 1) {
    cents = '0'+v;
  }
  if (cents.length === 3) {
    var centNumbers = cents.split('');
    dollar = dollar === '0' ? centNumbers[0] : dollar+centNumbers[0];
    cents = centNumbers[1]+centNumbers[2];
  }
  this.value = dollar+'.'+cents;
});

https://jsfiddle.net/apxh4eL2/4/

Edit:

After a while, I came up with a much cleaner solution.

$(document).on('input',':input',function(event) {
  if (this.value.length === 1) {this.value = '0'+this.value;}
  this.value = parseFloat(this.value.replace(/[^\d]/g,'').replace(/(\d\d?)$/,'.$1')).toFixed(2);
});

Demo: https://jsfiddle.net/apxh4eL2/9/