Did you add the locale to the toLocaleString function? for example javascript var number = 12345.543; number.toLocaleString('en') if i print the above code in the console it shows "12,345.543" Answer from Richard Price on teamtreehouse.com
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 - By specifying the maximumFractionDigits option, you can control the number of decimal places displayed. Formatting numbers as currency is common in e-commerce and financial applications. You can use JavaScriptโ€™s toLocaleString() method to format currency. Here is an example of formatting numbers as currency with commas:
๐ŸŒ
Byby
byby.dev โ€บ js-format-numbers-commas
How to format numbers with commas in JavaScript
In some countries, including many European countries, the comma is used as the decimal separator (eg: 3,14), the period is used as the thousands separator (eg: 1.000.000).
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ bytes โ€บ format-numbers-with-commas-in-javascript
Format Numbers with Commas in JavaScript
August 7, 2023 - However, keep in mind that toLocaleString() will keep all digits after the decimal. So 1234567.890123 would become "1,234,567.890123". If you need a bit more control over the formatting, regular expressions can help: function formatNumberWithCommas(number) { return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } const number = 1234567.89; console.log(formatNumberWithCommas(number)); // Outputs: "1,234,567.89" Link: This function uses regular expressions to insert commas after every third digit from right to left, providing the desired formatting.
๐ŸŒ
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 - Supports additional options, like setting minimum or maximum decimal places. Additional examples: console.log(num.toLocaleString("en-US", { minimumFractionDigits: 2 })); // "1,234,567.89" console.log(num.toLocaleString("de-DE")); // "1.234.567,89" (German locale) Using Intl.NumberFormat A more advanced method for custom formatting: const formatter = new Intl.NumberFormat("en-US"); console.log(formatter.format(1234567.89)); // Output: "1,234,567.89" Handling Large Numbers JavaScript has a maximum safe integer value (9007199254740991).
Find elsewhere
๐ŸŒ
EyeHunts
tutorial.eyehunts.com โ€บ home โ€บ javascript format number with commas and decimal places | example
JavaScript format number with commas and decimal places | Code
December 13, 2022 - A simple example code converts a given number into number value format with a comma and two decimal points. This turns a number 1234.567 in to 1,234.567. <!DOCTYPE html> <html> <body> <script> var n = 1234.567; var val = Math.round(Number(n) *100) / 100; var parts = val.toString().split("."); var num = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : ""); console.log(num); console.log(typeof(num)) </script> </body> </html> ... <script> var n = 1234.567; function numberWithCommas(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } console.log(numberWithCommas(n)); </script>
๐ŸŒ
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....
๐ŸŒ
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.
๐ŸŒ
Javatpoint
javatpoint.com โ€บ javascript-format-numbers-with-commas
JavaScript format numbers with commas - javatpoint
JavaScript format numbers with commas with javascript tutorial, introduction, javascript oops, application of javascript, loop, variable, objects, map, typedarray etc.
๐ŸŒ
sebhastian
sebhastian.com โ€บ javascript-format-number-commas
JavaScript format number with commas (example included) | sebhastian
July 8, 2022 - You can transform a number value into a comma-separated string by using 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.
๐ŸŒ
Decodingweb
decodingweb.dev โ€บ add-commas-to-numbers-in-javascript
Add commas to numbers in JavaScript with these simple methods
September 22, 2023 - We usually achieve this by using commas as thousands separators with the help of JavaScript. ... There are plenty of ways to format your numbers.
๐ŸŒ
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.
๐ŸŒ
HashBangCode
hashbangcode.com โ€บ article โ€บ format-numbers-commas-javascript
Format Numbers With Commas In JavaScript | #! code
outD : This is what to change the decimal character into. sep : This is the separator, which is usually a comma.