-2

Can you help me changing that variable to make commas as thousand separators?

var number1 = 123456789;
$(function(){
    document.getElementById("test").innerHTML("Var number1 is: " + number1); //i want that to display with commas
}

I don't understand answers on other questions like that. Thanks

Mg112
  • 27
  • 2
  • 9
  • Sounds like you want to format the number `123456789` to `123,456,789` using JavaScript - did I get it right? Possibly this would help: http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript – blurfus Mar 14 '14 at 19:10

1 Answers1

0

You may look at some answers here:

http://www.queness.com/post/9806/5-missing-javascript-number-format-functions

but here's the code from the same page:

function CommaFormatted(amount) {
    var delimiter = ","; // replace comma if desired
    amount = new String(amount);
    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;
}

/**
*   Usage:  CommaFormatted(12345678);
*   result: 12,345,678
**/
blurfus
  • 13,485
  • 8
  • 55
  • 61