I used the idea from Kerry's answer, but I simplified it since I was just looking for something simple for my specific purpose. Here is what I have:

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

function numberWithCommas(x) {
    return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}

function test(x, expect) {
    const result = numberWithCommas(x);
    const pass = result === expect;
    console.log(`${pass ? "✓" : "ERROR ====>"} {result}`);
    return pass;
}

let failures = 0;
failures += !test(0,        "0");
failures += !test(100,      "100");
failures += !test(1000,     "1,000");
failures += !test(10000,    "10,000");
failures += !test(100000,   "100,000");
failures += !test(1000000,  "1,000,000");
failures += !test(10000000, "10,000,000");
if (failures) {
    console.log(`${failures} test(s) failed`);
} else {
    console.log("All tests passed");
}
.as-console-wrapper {
    max-height: 100% !important;
}


The regex uses two lookahead assertions:

  • a positive one to look for any point in the string that has a multiple of 3 digits in a row after it,
  • a negative assertion to make sure that point only has exactly a multiple of 3 digits. The replacement expression puts a comma there.

For example, if you pass it 123456789.01, the positive assertion will match every spot to the left of the 7 (since 789 is a multiple of 3 digits, 678 is a multiple of 3 digits, 567, etc.).

The negative assertion checks that the multiple of 3 digits does not have any digits after it. 789 has a period after it so it is exactly a multiple of 3 digits, so a comma goes there. 678 is a multiple of 3 digits, but it has a 9 after it, so those 3 digits are part of a group of 4, and a comma does not go there. Similarly for 567.

456789 is 6 digits, which is a multiple of 3, so a comma goes before that. 345678 is a multiple of 3, but it has a 9 after it, so no comma goes there. And so on. The \B keeps the regex from putting a comma at the beginning of the string.

neu-rah mentioned that this function adds commas in undesirable places if there are more than 3 digits after the decimal point. If this is a problem, you can use this function:

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

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

function test(x, expect) {
    const result = numberWithCommas(x);
    const pass = result === expect;
    console.log(`${pass ? "✓" : "ERROR ====>"} {result}`);
    return pass;
}

let failures = 0;
failures += !test(0              , "0");
failures += !test(0.123456       , "0.123456");
failures += !test(100            , "100");
failures += !test(100.123456     , "100.123456");
failures += !test(1000           , "1,000");
failures += !test(1000.123456    , "1,000.123456");
failures += !test(10000          , "10,000");
failures += !test(10000.123456   , "10,000.123456");
failures += !test(100000         , "100,000");
failures += !test(100000.123456  , "100,000.123456");
failures += !test(1000000        , "1,000,000");
failures += !test(1000000.123456 , "1,000,000.123456");
failures += !test(10000000       , "10,000,000");
failures += !test(10000000.123456, "10,000,000.123456");
if (failures) {
    console.log(`${failures} test(s) failed`);
} else {
    console.log("All tests passed");
}
.as-console-wrapper {
    max-height: 100% !important;
}

T.J. Crowder pointed out that now that JavaScript has lookbehind (support info), it can be solved in the regular expression itself:

function numberWithCommas(x) {
    return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}

function numberWithCommas(x) {
    return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}

function test(x, expect) {
    const result = numberWithCommas(x);
    const pass = result === expect;
    console.log(`${pass ? "✓" : "ERROR ====>"} {result}`);
    return pass;
}

let failures = 0;
failures += !test(0,               "0");
failures += !test(0.123456,        "0.123456");
failures += !test(100,             "100");
failures += !test(100.123456,      "100.123456");
failures += !test(1000,            "1,000");
failures += !test(1000.123456,     "1,000.123456");
failures += !test(10000,           "10,000");
failures += !test(10000.123456,    "10,000.123456");
failures += !test(100000,          "100,000");
failures += !test(100000.123456,   "100,000.123456");
failures += !test(1000000,         "1,000,000");
failures += !test(1000000.123456,  "1,000,000.123456");
failures += !test(10000000,        "10,000,000");
failures += !test(10000000.123456, "10,000,000.123456");
if (failures) {
    console.log(`${failures} test(s) failed`);
} else {
    console.log("All tests passed");
}
.as-console-wrapper {
    max-height: 100% !important;
}

(?<!\.\d*) is a negative lookbehind that says the match can't be preceded by a . followed by zero or more digits. The negative lookbehind is faster than the split and join solution (comparison), at least in V8.

Answer from Elias Zamaria on Stack Overflow
Top answer
1 of 16
3954

I used the idea from Kerry's answer, but I simplified it since I was just looking for something simple for my specific purpose. Here is what I have:

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

function numberWithCommas(x) {
    return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}

function test(x, expect) {
    const result = numberWithCommas(x);
    const pass = result === expect;
    console.log(`${pass ? "✓" : "ERROR ====>"} {result}`);
    return pass;
}

let failures = 0;
failures += !test(0,        "0");
failures += !test(100,      "100");
failures += !test(1000,     "1,000");
failures += !test(10000,    "10,000");
failures += !test(100000,   "100,000");
failures += !test(1000000,  "1,000,000");
failures += !test(10000000, "10,000,000");
if (failures) {
    console.log(`${failures} test(s) failed`);
} else {
    console.log("All tests passed");
}
.as-console-wrapper {
    max-height: 100% !important;
}


The regex uses two lookahead assertions:

  • a positive one to look for any point in the string that has a multiple of 3 digits in a row after it,
  • a negative assertion to make sure that point only has exactly a multiple of 3 digits. The replacement expression puts a comma there.

For example, if you pass it 123456789.01, the positive assertion will match every spot to the left of the 7 (since 789 is a multiple of 3 digits, 678 is a multiple of 3 digits, 567, etc.).

The negative assertion checks that the multiple of 3 digits does not have any digits after it. 789 has a period after it so it is exactly a multiple of 3 digits, so a comma goes there. 678 is a multiple of 3 digits, but it has a 9 after it, so those 3 digits are part of a group of 4, and a comma does not go there. Similarly for 567.

456789 is 6 digits, which is a multiple of 3, so a comma goes before that. 345678 is a multiple of 3, but it has a 9 after it, so no comma goes there. And so on. The \B keeps the regex from putting a comma at the beginning of the string.

neu-rah mentioned that this function adds commas in undesirable places if there are more than 3 digits after the decimal point. If this is a problem, you can use this function:

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

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

function test(x, expect) {
    const result = numberWithCommas(x);
    const pass = result === expect;
    console.log(`${pass ? "✓" : "ERROR ====>"} {result}`);
    return pass;
}

let failures = 0;
failures += !test(0              , "0");
failures += !test(0.123456       , "0.123456");
failures += !test(100            , "100");
failures += !test(100.123456     , "100.123456");
failures += !test(1000           , "1,000");
failures += !test(1000.123456    , "1,000.123456");
failures += !test(10000          , "10,000");
failures += !test(10000.123456   , "10,000.123456");
failures += !test(100000         , "100,000");
failures += !test(100000.123456  , "100,000.123456");
failures += !test(1000000        , "1,000,000");
failures += !test(1000000.123456 , "1,000,000.123456");
failures += !test(10000000       , "10,000,000");
failures += !test(10000000.123456, "10,000,000.123456");
if (failures) {
    console.log(`${failures} test(s) failed`);
} else {
    console.log("All tests passed");
}
.as-console-wrapper {
    max-height: 100% !important;
}

T.J. Crowder pointed out that now that JavaScript has lookbehind (support info), it can be solved in the regular expression itself:

function numberWithCommas(x) {
    return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}

function numberWithCommas(x) {
    return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}

function test(x, expect) {
    const result = numberWithCommas(x);
    const pass = result === expect;
    console.log(`${pass ? "✓" : "ERROR ====>"} {result}`);
    return pass;
}

let failures = 0;
failures += !test(0,               "0");
failures += !test(0.123456,        "0.123456");
failures += !test(100,             "100");
failures += !test(100.123456,      "100.123456");
failures += !test(1000,            "1,000");
failures += !test(1000.123456,     "1,000.123456");
failures += !test(10000,           "10,000");
failures += !test(10000.123456,    "10,000.123456");
failures += !test(100000,          "100,000");
failures += !test(100000.123456,   "100,000.123456");
failures += !test(1000000,         "1,000,000");
failures += !test(1000000.123456,  "1,000,000.123456");
failures += !test(10000000,        "10,000,000");
failures += !test(10000000.123456, "10,000,000.123456");
if (failures) {
    console.log(`${failures} test(s) failed`);
} else {
    console.log("All tests passed");
}
.as-console-wrapper {
    max-height: 100% !important;
}

(?<!\.\d*) is a negative lookbehind that says the match can't be preceded by a . followed by zero or more digits. The negative lookbehind is faster than the split and join solution (comparison), at least in V8.

2 of 16
3275

I'm surprised nobody mentioned Number.prototype.toLocaleString. It's implemented in JavaScript 1.5 (which was introduced in 1999), so it's basically supported across all major browsers.

var n = 34523453.345;
console.log(n.toLocaleString());    // "34,523,453.345"

It also works in Node.js as of v0.12 via inclusion of Intl.

If you want something different, Numeral.js might be interesting.

🌐
DEV Community
dev.to › onlinemsr › big-numbers-no-worries-javascript-format-number-with-commas-n6j
Big Numbers, No Worries: JavaScript Format Number With Commas - DEV Community
March 23, 2024 - Look at this example of using toFixed() in JavaScript: // Format number with comma using toFixed() var number = 123456789.123; // Convert the numberber into a string, with two decimal places var fixednumber = number.toFixed(2); // Split the string into two parts: the integer part and the decimal part var parts = fixednumber.split("."); // Add commas to the integer part, using a regular expression var integerPart = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ","); // Join the two parts with a dot var formattednumber = integerPart + "." + parts[1]; // Display the formatted numberber console.log(formattednumber); // Output: 123,456,789.12
🌐
Reddit
reddit.com › r/javascript › how do i insert comma between numbers?
r/javascript on Reddit: How do I insert comma between numbers?
December 12, 2016 -

I'm having javascript do number calculations for me. I need to insert a comma between ever 3rd number. For instance, the number currently appears as $1234567.89 but I need it to appear as $1,234,567.89. How do I fix it? This my current code:

"$ " + (var1 + var2).toFixed(2)

Thanks!

*grammar

Top answer
1 of 3
2
u/zappsg 's recommendation is a lot better, but for the purpose of learning, here's one way you could do it with some comments explaining how it works: function formatNumber(num) { // If the number is less than zero, make a note of this var isNegative = num < 0; // Convert the number to a string with two decimal palces, // then split that string into an array of characters. If the // number was lower than zero, throw away the minus sign var tempNumArray = isNegative ? num.toFixed(2).split('').slice(1) : num.toFixed(2).split(''); // We're gonna keep track of the period so we know not to add commas after it var dotIndex = tempNumArray.indexOf('.'); // The number of digits to the left of the decimal point // is 3 less than the length of the array var integerCount = tempNumArray.length - 3; // Map over every digit in the array var formattedArray = tempNumArray.map(function(digit, index, arr) { // Check if we're in the whole digits var isBeforeDot = (index + 1) < dotIndex; // If we're in the whole digits, check if the number of whole digits still left to go % 3 is 0. // If it is, we need to add a comma, so we'll return the current digit plus a comma. if (isBeforeDot && (integerCount - (index + 1)) % 3 === 0) { return digit + ','; } else { // Otherwise we just return the digit. return digit; } // Join our newly mapped array back into a string }).join(''); // If our number was negative return it with a minus sign in front, // otherwise just return the number return isNegative ? '-' + formattedArray : formattedArray; } Then, to use it, you'd just do: "$ " + formatNumber(var1 + var2);
2 of 3
1
It's built into JavaScript already. By default it tries to detect the client's locale and uses this. You can force it, if you want. See here for details . var number = 1234567.89; var result = '$' + number.toLocaleString('en'); //force to comma as separator http://codepen.io/anon/pen/woYaep?editors=1010
🌐
MSR
rajamsr.com › home › javascript format number with commas: 5 best ways
JavaScript Format Number with Commas: 5 Best Ways | MSR - Web Dev Simplified
March 19, 2024 - How to format a number with commas and a dollar sign in JavaScript? The numberWithCommasAndDollar() function formats a given number by adding a dollar sign and commas for thousands, ensuring it has two decimal places.
🌐
javaspring
javaspring.net › blog › how-to-use-tolocalestring-and-tofixed-2-in-javascript
How to Use `toLocaleString()` and `toFixed(2)` in JavaScript: Format Numbers with Commas and 2 Decimal Places — javaspring.net
Show large revenue numbers with commas and 2 decimals: const revenue = 1234567.89; const formattedRevenue = revenue.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); console.log(`Annual Revenue: $${formattedRevenue}`); // "Annual Revenue: $1,234,567.89" Calculate tax and round to 2 decimals for storage in a database: const subtotal = 45.99; const taxRate = 0.08; // 8% tax const tax = (subtotal * taxRate).toFixed(2); // "3.68" console.log(`Tax: $${tax}`); // "Tax: $3.68"
🌐
SheCodes
shecodes.io › athena › 287246-explaining-the-tofixed-method-in-javascript
[JavaScript] - Explaining the toFixed() Method in | SheCodes
Learn how to use the toFixed() method in JavaScript to format numbers with a specified number of decimal places.
Find elsewhere
🌐
Sanjoy K. Paul
skpaul.me › home › blog › convert a number to a comma separated value or string with decimal point in javascript
Convert a number to a Comma separated value or string with Decimal point in JavaScript
June 17, 2021 - /** * Convert number to Comma separated decimal value * @param {int} x * @param {string} local default value "en-IN" * @returns string */ function numberWithCommasAndDecimalPoint(x, local) { local = local.length > 0 ? local : "en-IN"; x = parseFloat(x).toFixed(2); var parts = x.toString().split("."); parts[0] = parseInt(parts[0]).toLocaleString("en-IN"); return parts.join("."); }
🌐
javaspring
javaspring.net › blog › javascript-using-tolocalestring-tofixed
JavaScript: How to Use `toLocaleString()` and `toFixed()` to Format Numbers with Commas and 2 Decimal Places — javaspring.net
For financial data, combine currency formatting with commas: const revenue = 1234567.89; const formattedRevenue = revenue.toLocaleString('en-US', { style: 'currency', currency: 'USD' }); console.log(formattedRevenue); // "$1,234,567.89" Both methods rely on JavaScript’s floating-point arithmetic, which can have rounding errors. For example: const num = 0.1 + 0.2; // 0.30000000000000004 console.log(num.toFixed(2)); // "0.30" (correctly rounded) console.log(num.toLocaleString('en-US', { minimumFractionDigits: 2 })); // "0.30" This is rarely an issue for display purposes, but for critical financial calculations, use a library like decimal.js.
Top answer
1 of 3
392

Taken from MDN:

Syntax

numObj.toLocaleString([locales [, options]])

toLocaleString takes 2 arguments. The first is the locale, the second are the options. As for the options, you are looking for:

minimumFractionDigits

The minimum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number and percent formatting is 0; the default for currency formatting is the number of minor unit digits provided by the ISO 4217 currency code list (2 if the list doesn't provide that information).

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

To be able to set the options without setting the locale, you can pass undefined as first argument:

var num = 2046430;
num.toLocaleString(undefined, {minimumFractionDigits: 2}) // 2,046,430.00

However this also allows the fraction to be longer than 2 digits. So we need to look for one more option called maximumFractionDigits. (Also on that MDN page)

var num = 2046430.123;


console.log(num.toLocaleString(undefined, {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
})); // 2,046,430.12

2 of 3
1

I came here because I would like to show the currency symbol (R$) in addition show two digits after the decimal point in the result.

Initially I was trying the following code:

`Amount ${(gas * litros).toFixed(2)
  .toLocaleString('pt-BR', {style: 'currency', currency: 'BRL'})}`

Expected output: Total a pagar R$ 20.95

Output: Total a pagar 20.95

So, with the answers above, I tried without the toFixed():

`Total a pagar ${(gas * litros)
    .toLocaleString('pt-BR', {style: 'currency', currency: 'BRL', minimumFractionDigits: 2})}`

Output: Total a pagar R$ 15,80

🌐
Queness
queness.com › post › 9806 › 5-missing-javascript-number-format-functions
5 Missing Javascript Number Format Functions
function round(number, decimals){ return parseFloat(number.toFixed(decimals)); } Source: Hott dogg · These two javascript functions add commas between every third digit (right to left) for numbers 1000 and larger. This makes big number easier to comprehend.
🌐
W3Schools
w3schools.com › jsref › jsref_tofixed.asp
JavaScript toFixed() Method
The toFixed() method rounds the string to a specified number of decimals. If the number of decimals are higher than in the number, zeros are added. ... If you want to use W3Schools services as an educational institution, team or enterprise, ...
🌐
CSS-Tricks
css-tricks.com › snippets › javascript › comma-values-in-numbers
Put Comma Values in Numbers | CSS-Tricks
December 19, 2009 - Any reason not to just use ... added in the right places. ... Javascript has a method called toFixed() that will format your numbers so they have commas and even let you add 2 decimals....
🌐
Flavio Copes
flaviocopes.com › how-to-comma-dot-javascript
How to change commas into dots with JavaScript
June 18, 2020 - The g flag in the regex makes sure that if there are multiple instances of a comma (or dot, in the second example) they are all converted. This is not something that applies to our use case, and I think we need to do more validation to check ...
🌐
Creative COW
creativecow.net › forums › adobe after effects expressions › comma instead of dot – javascript
Comma instead of dot – javascript - Adobe After Effects Expressions - Creative COW
Activity › Forums › Adobe After Effects Expressions › Comma instead of dot – javascript ... I need to transform the “dot” in a “comma” in this expresion used in a Bar Graph. I’ve tried to put “.toLocaleString(‘de-DE’)” before and after this line – “.toFixed(textN...
🌐
Stack Overflow
stackoverflow.com › questions › 6153382 › string-tofixed-with-javascript
html - String toFixed with javascript? - Stack Overflow
input can be a string of digits with or without commas, minus sign and decimal, or a number · function addCommas2decimals(n){ n= Number(String(n).replace(/[^-+.\d]+/g, '')); if(isNaN(n)){ throw new Error('Input must be a number'); } n= n.toFixed(2); var rx= /(\d+)(\d{3})/; return n.replace(/^\d+/, function(w){ while(rx.test(w)){ w= w.replace(rx, '$1,$2'); } return w; }); } var s= '1234567.890123' addCommas2decimals(s) /* returned value: (String) 1,234,567.89 */ Share ·