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
🌐
Wix Studio
forum.wixstudio.com › ask the community
How to Display Numbers with a Comma Separator - Ask the community - Community Support Forum | Wix Studio
September 26, 2019 - Hey Guys, Struggling with understanding how to get my code to display commas. While I know its been attempted to be answered before my situation is a bit unique I think. In my my database I have both text and numbers (different columns). The numbers are inputted as 0000.00, but displayed with ...
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.

Discussions

Javascript Formatting numbers with commas
Carlo Sabogal is having issues with: My level of js is very basic. Currently I am learning about basic number operations. My question is: How do you display numbers on the screen wi... More on teamtreehouse.com
🌐 teamtreehouse.com
5
May 15, 2015
How do I insert comma between numbers?
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); More on reddit.com
🌐 r/javascript
3
1
December 12, 2016
Formatting a number with commas as a thousand digits without converting it into a string
I’ve tried this but when I checked it with console.log(isNaN(conversion));, it returns true. How do you format this without it converting into a string? const income = Number(8000); const conversion = income.toLocaleString(navigator.language, { minimumFractionDigits: 2 }); console.log(is... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
1
1
March 7, 2022
Adding comma to a number
Hi , I wanted to add comma to a number Could you please guide me here… Example 7000 output 7,000 Thanks More on forum.uipath.com
🌐 forum.uipath.com
1
0
August 30, 2023
🌐
Crio
crio.do › blog › format-numbers-with-commas-as-thousands-separators-2025-javascript-criodo
How to Format a Number with Commas as Thousands Separators?
December 26, 2024 - Formatting numbers with commas as thousands separators is essential for enhancing readability, especially when displaying large numbers in user interfaces. This is a common requirement for financial data, statistics, and other applications. Here’s a concise and effective way to format numbers using JavaScript...
🌐
Medium
medium.com › @onlinemsr › big-numbers-no-worries-javascript-format-number-with-commas-17ec7f878834
Big Numbers, No Worries: JavaScript Format Number With Commas
March 23, 2024 - If you are a web developer, you ... number, like 1000000 or 1,000,000, for better readability. Using the toLocaleString() method you can format numbers with commas....
🌐
Stack Abuse
stackabuse.com › bytes › format-numbers-with-commas-in-javascript
Format Numbers with Commas in JavaScript
August 7, 2023 - Formatting numbers with commas is a common requirement, enhancing the readability and overall user experience. While JavaScript provides native methods like toLocaleString, you can also achieve this through regular expressions or even employ libraries like Lodash.
🌐
Favtutor
favtutor.com › articles › format-numbers-commas-javascript
Format Numbers with Commas in JavaScript (with code)
February 5, 2024 - Learn how to format numbers by adding commas using JavaScript using the toLocaleString() method and using regular expressions.
🌐
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 - Do you want to make your numbers look more readable and friendly? You can do that with the toLocaleString() method in JavaScript! This method lets you format numbers based on the user’s location and preferences.
Find elsewhere
🌐
Codingexercises
codingexercises.com › format-a-number-with-a-comma-as-a-thousands-separator-js
Format a number with comma as a thousands separator in JS
January 12, 2021 - In JS, we can add a comma as thousands separator using the toLocaleString() method, or using Intl.NumberFormat().format, or using a RegExp. In this tutorial, we'll cover the first two listed means of doing this.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Intl › NumberFormat
Intl.NumberFormat - JavaScript | MDN
In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: ... const number = 123456.789; // German uses comma as decimal separator and period for thousands console.log(new Intl.NumberFormat("de-DE").format(number)); // 123.456,789 // Arabic in most Arabic speaking countries uses real Arabic digits console.log(new Intl.NumberFormat("ar-EG").format(number)); // ١٢٣٤٥٦٫٧٨٩ // India uses thousands/lakh/crore separators console.log(new Intl.NumberFormat("en-IN").format(number)); // 1,23,456.789 // the nu extension key requests a numbering system, e.g.
🌐
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
🌐
TypeOfNaN
typeofnan.dev › how-to-add-thousandths-place-comma-every-three-digits-in-javascript
How to Add a Thousandths Place Comma (Every Three Digits) in JavaScript | TypeOfNaN
December 29, 2020 - If our input is a number, we’ll want to make sure to covert it to a string before applying the regex. function addCommas(num) { return num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,'); } addCommas(1000); // 1,000 addCommas(1000000); // 1,000,000 addCommas(100); // 1000 · And that’s it! A couple fairly straightforward ways to add commas to your large numbers.
🌐
DEV Community
dev.to › lavary › add-commas-to-numbers-in-javascript-explained-with-examples-27k8
Add commas to numbers in JavaScript (Explained with examples) - DEV Community
February 6, 2023 - Consequently, The replace() method places a comma in each match. Formatting numbers can be done in a variety of ways in JavaScript.
🌐
Sabe
sabe.io › blog › javascript-format-numbers-commas
Format Numbers with Commas in JavaScript | Sabe
March 6, 2022 - The best way to format numbers in JavaScript is to use the toLocaleString() method. This method exists on the Number object and will return a string with the number formatted with commas.
🌐
Medium
medium.com › @noffybarudwale › javascript-format-numbers-with-commas-and-decimals-86b68ec5b180
JavaScript : Format numbers with commas and decimals. | by Nofij Barudwale | Medium
October 13, 2021 - There are many different ways of printing an integer with a comma as a thousands separators in JavaScript. I found a good function that details how to and thought I would reproduce it here. It basically takes any number and turns it into formatted string with the thousands separated by commas and decimals.
🌐
LambdaTest Community
community.lambdatest.com › general discussions
What’s the best way to format numbers with commas as thousands separators in JavaScript? - LambdaTest Community
October 15, 2025 - I’m trying to display large numbers in a more readable format in JavaScript by adding commas as thousands separators. For example, I’d like a value like 1234567 to be shown as 1,234,567. I currently have a working solut…
🌐
Lingo
lingo.dev › en › javascript-i18n › format-numbers-thousands-separators
How to format numbers with thousands separators - JavaScript i18n
The number 1234567 becomes 1,234,567 with comma separators. The term "thousands separator" comes from the most common use case where separators appear after every three digits. However, the same mechanism applies to any digit grouping, whether for hundreds of thousands, millions, or billions. Without separators, the digits run together and require careful counting. With separators, your eye can quickly identify the magnitude of the number.