treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Put Comma Values in Numbers

Last updated on:

This function assumes what is being submitted to it is a string, with a decimal point and two places after the decimal. To get your number into that format first, use this.

Then this function will properly comma separate the number. For example, 2345643.00 will return 2,345,643.00

function CommaFormatted(amount) {
	var delimiter = ","; // replace comma if desired
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3) {
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d.length < 1) { amount = n; }
	else { amount = n + '.' + d; }
	amount = minus + amount;
	return amount;
}
View Comments

Comments

  1. dyllon
    Permalink to comment#

    is there something like this for PHP?

  2. Permalink to comment#

    Ohhh.. Wonderful code snippet. Searching for long time.

  3. Jack

    this is how I do it:

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

  4. Zidu
    Permalink to comment#

    How about this script.
    Any chance to insert a comma or a space between the numbers in this counter?

    kasa=new Date(2008 ,12 ,60 ,30 ,01);
    setInterval(function(){
    with(Math){
    var w=floor(((new Date())-kasa)/1000),lr,dr,mr,
    l=floor(w/31536000),d=floor((lr=w%31536000)/86400),
    g=floor((dr=lr%86400)/3600),m=floor((mr=dr%3600)/60),
    s=floor(mr%60);
    document.getElementById(‘money’).innerHTML=
    (l?l+’ l., ‘:”)+d+’ dni,’+g+’ godz., ‘
    +m+’ min., ‘+s+’ sek.’;
    }
    },1000);
    setInterval(function(){
    document.getElementById(‘MoneyCounter’).innerHTML=
    ((new Date())-kasa);
    },130);

  5. Anonymous
    Permalink to comment#

    Here’s the same thing in 1 line. If anybody can do better, do share.

    function commas(str) {
        return str.replace(/.(?=(?:.{3})+$)/g, '$&,');
    }
  6. Can’t do better making it shorter, but I can fix it so it takes numeric arguments!

    function commas(str) {
    return (str+”").replace(/.(?=(?:.{3})+$)/g, ‘$&,’);
    }

  7. Hmm… and make it handle decimals in a hackish way. ;-)

    function commas(str) {return (str+”").replace(/.(?=(?:[0-9]{3})+\b)/g, ‘$&,’);

Leave a Comment

Use markdown or basic HTML and be nice.