user2826169
user2826169

Reputation: 285

How to convert a price into a valid price format in javascript?

I have the following html.

<input type="text" id="Price">

When the user enters a price amount in this input field,that should be automatically converted to a valid price format.

suppose a user enters 9200000,it should be automatically converted to 9,200,000.

So can anyboby explain how it can be done in javascript ?

It should be done in the keyDown,keypress or keyup events of this field.

Thanks

Upvotes: 0

Views: 246

Answers (3)

Ajith S
Ajith S

Reputation: 2917

This is from How can I format numbers as money in JavaScript?

Number.prototype.formatMoney = function(c, d, t){
var n = this, 
    c = isNaN(c = Math.abs(c)) ? 2 : c, 
    d = d == undefined ? "." : d, 
    t = t == undefined ? "," : t, 
    s = n < 0 ? "-" : "", 
    i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", 
    j = (j = i.length) > 3 ? j % 3 : 0;
   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
 };
alert((123456789.12345).formatMoney(2, '.', ','));

Upvotes: 1

Satpal
Satpal

Reputation: 133403

You can try this, I have used function in reference

 //Attach event
var el = document.getElementById("Price");
el.onkeydown = function(evt) {
    evt = evt || window.event;
    this.value = addCommas(stripNonNumeric(this.value));
};

// This function removes non-numeric characters
function stripNonNumeric( str )
{
  str += '';
  var rgx = /^\d|\.|-$/;
  var out = '';
  for( var i = 0; i < str.length; i++ )
  {
    if( rgx.test( str.charAt(i) ) ){
      if( !( ( str.charAt(i) == '.' && out.indexOf( '.' ) != -1 ) ||
             ( str.charAt(i) == '-' && out.length != 0 ) ) ){
        out += str.charAt(i);
      }
    }
  }
  return out;
}

function addCommas(nStr)
{
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

Working Demo

Upvotes: 1

dijipiji
dijipiji

Reputation: 3109

Add an event listener on the input and write a function to insert the commas into your input value which the listener calls when you get a keyDown event.

Upvotes: 0

Related Questions