Thursday, March 12, 2015

Javascript display numbers with commas

function commaSeparated(val){
    while (/(\d+)(\d{3})/.test(val.toString())){
      val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
    }
    return val;
}

// Call Function
console.log(commaSeparated(1)); // 1
console.log(commaSeparated(10)); // 10
console.log(commaSeparated(100)); // 100
console.log(commaSeparated(1000)); // 1,000
console.log(commaSeparated(10000)); //10,000

No comments:

Post a Comment