0

Possible Duplicate:
How can I format numbers as money in JavaScript?

I am working on a site, it has a input field for price. i need to format the price value something like the following.

if a user enter "1000000" it should replace with "1,000,000" is it possible?

Any help?

Community
  • 1
  • 1
Nevin
  • 205
  • 1
  • 4
  • 12

3 Answers3

2

You need custom function like this :

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;
}
Ta Duy Anh
  • 1,478
  • 9
  • 16
1

You can do as following:

function numberWithCommas(n) {
    var parts=n.toString().split(".");
    return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}

DEMO: http://jsfiddle.net/e9AeK/

Eli
  • 14,779
  • 5
  • 59
  • 77
1

A slight modification to the code of Taiki. Because if user enter 1000000 it will produce 1,000,000. but if the user use Backspace key to remove "0" it will not work.

function addPriceFormat()
{
    var numb='';
    nStr = document.getElementById('txt').value;
    my = nStr.split(',');
    var Len = my.length;
    for (var i=0; i<Len;i++){numb = numb+my[i];}
    x = numb.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');
    }
    formated = x1 + x2;
    document.getElementById('txt').value = formated;
}
Nevin
  • 205
  • 1
  • 4
  • 12