Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 804689
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T23:57:34+00:00 2026-05-14T23:57:34+00:00

I am trying to print an integer in JavaScript with commas as thousands separators.

  • 0

I am trying to print an integer in JavaScript with commas as thousands separators. For example, I want to show the number 1234567 as "1,234,567". How would I go about doing this?

Here is how I am doing it:

function numberWithCommas(x) {
    x = x.toString();
    var pattern = /(-?\d+)(\d{3})/;
    while (pattern.test(x))
        x = x.replace(pattern, "$1,$2");
    return x;
}

console.log(numberWithCommas(1000))

Is there a simpler or more elegant way to do it? It would be nice if it works with floats also, but that is not necessary. It does not need to be locale-specific to decide between periods and commas.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T23:57:34+00:00Added an answer on May 14, 2026 at 11:57 pm

    I used the idea from Kerry’s answer, but 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 ====>"} ${x} => ${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 2 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 ====>"} ${x} => ${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 ====>"} ${x} => ${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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 507k
  • Answers 507k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Any CUDA operation (except special asynchronious operations) will cause cudaThreadSynchronize()… May 16, 2026 at 3:54 pm
  • Editorial Team
    Editorial Team added an answer This is impossible. The user might leave the page because… May 16, 2026 at 3:54 pm
  • Editorial Team
    Editorial Team added an answer When you execute commands with String.execute(), they don't get parsed… May 16, 2026 at 3:54 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

I am trying to print out the name of the month not the integer
I'm trying to print the output of function only when it is true but
I am trying to print out an array of integers. I am getting a
I'm trying to print a pcl file programatically in c#. I'm using the following
I'm trying to print out a tree structure in my JSP page that looks
I am trying to print out a line that contains a mixture of a
I'm trying to print out the response data when I make a HTTP request,
I'm trying to 'pretty-print' out an array, using a syntax like: $outString = [;
I'm trying to instrument some code to catch and print error messages. Currently I'm
I have been trying to figure out how can we print a array hellically

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.