[Solved-6 Solutions] Print a number with commas as thousands separators in JavaScript - javascript tutorial



Problem:

How to print a number with commas as thousands separators in JavaScript ?

Solution 1:

HTML:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>To print an integer with commas as thousands separators</title>
</head>
<body>

</body>
</html>

JavaScript:

function thousands_separators(num)
  {
    var num_parts = num.toString().split(".");
    num_parts[0] = num_parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return num_parts.join(".");
  }

console.log(thousands_separators(1000));
console.log(thousands_separators(10000.23));
console.log(thousands_separators(100000));

Output:

1,000
10,000.23
100,000

Solution 2:

You can try this solution:

function numWithComma(a) {
    return a.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

The "\B" keeps the regex from putting a comma at the beginning of the string.

This function adds commas in undesirable places if there are more than 3 digits after the decimal point. To fix this problem, you can use like this:

const numberWithCommas = (a) => {
  var parts = a.toString().split(".");
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  return parts.join(".");
}

Solution 3:

Simple solution to solve these problem is Number.prototype.toLocaleString. The toLocaleString() method returns a string with a language-sensitive representation of a number.

var number = 987654321;

toLocaleString:

number.toLocaleString(); // "987,654,321"
// A more complex example: 
var number2 = 9876.54321; // floating point example
number2.toLocaleString(undefined, {
	maximumFractionDigits: 2
}); // "9,876.54"

NumberFormat does not supported in Safari browser.

var nf = new Intl.NumberFormat();
nf.format(number); // "1,234,567,890"

Solution 4:

Use this function to overcome all the NumberFormat issues

function number_format(number, decimals, dec_point, thousands_sep) {                             
        var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        toFixedFix = function (n, prec) {
            // Fix for IE parseFloat(0.55).toFixed(0) = 0;
            var k = Math.pow(10, prec);
            return Math.round(n * k) / k;
        },
        s = (prec ? toFixedFix(n, prec) : Math.round(n)).toString().split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

Solution 5:

The best way is to split the number format into several parts.

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


Related Searches to Print a number with commas as thousands separators in JavaScript -javascript tutorial