Just split into two parts with '.' and format them individually.

function commafy( num ) {
    var str = num.toString().split('.');
    if (str[0].length >= 5) {
        str[0] = str[0].replace(/(\d)(?=(\d{3})+1,');
    }
    if (str[1] && str[1].length >= 5) {
        str[1] = str[1].replace(/(\d{3})/g, '$1 ');
    }
    return str.join('.');
}
Answer from Ghostoy on Stack Overflow
🌐
CodePen
codepen.io β€Ί SalmanShaikh β€Ί pen β€Ί VvKgRj
add comma in number's input every after 3 digits
Watch and manage commas in number's input every after 3 digits then sanitize on leave so you can pass pure integer value....
Discussions

jquery - Add comma to numbers every three digits - Stack Overflow
How can I format numbers using a comma separator every three digits using jQuery? For example: ╔═══════════╦═════════════╗ β•‘ Input β•‘ Output β•‘ ╠═══════════╬═════════════╣ β•‘ 298 β•‘ ... More on stackoverflow.com
🌐 stackoverflow.com
January 8, 2016
javascript - How can I add a comma after each 3 digits? - Stack Overflow
See Add commas or spaces to group every three digits. ... In your current pattern (\d{3}) you add a comma after matching 3 digits and also when there is already a comma following the 3 digits. More on stackoverflow.com
🌐 stackoverflow.com
javascript - Add Comma After Every Three Digits in Input Value After OnClick Event - Stack Overflow
I have a table/form that calculates monthly payments for a mortgage. When the calculate button is pressed, a JavaScript function will make a calculation based on the values of the inputs and set the More on stackoverflow.com
🌐 stackoverflow.com
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
🌐
Devncoffee
devncoffee.com β€Ί add-commas-to-numbers-in-javascript
4 Ways To Add Commas To Numbers In Javascript – Dev + Coffee
Thus, replace(/\B(?=(\d{3})+(?!\d))/g, ",") will insert a comma for every 3 digits. While this is a one-liner, writing a regular expression is β€œvery inhuman”. How does one even come up with that pattern? Master Coffee has a β€œlazy hack”, just ask ChatGPT to β€œWrite a Javascript regular ...
🌐
C# Corner
c-sharpcorner.com β€Ί blogs β€Ί javascriptadd-commas-into-your-given-number-after-every-three-digits1
Javascript-Add commas into your given number after every three digits.
April 30, 2020 - <script type="text/javascript"> function AddComma(MyString) { var objRegex = new RegExp('(-?[0-9]+)([0-9]{3})'); //Check For Criteria.... while(objRegex.test(MyString)) { //Add Commas After Every Three Digits Of Number...
Top answer
1 of 7
2

In your current pattern (\d{3}) you add a comma after matching 3 digits and also when there is already a comma following the 3 digits.

What you might do is match 3 digits using a negative lookahead (?!,) to assert what follows is not a comma:

(\d{3}(?!,))

$("#annual_sales").on('keyup', function() {
  $(this).val($(this).val().replace(/(\d{3}(?!,))/g, "$1,"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />

If you don't want the comma at the end of the line you could use an alternation in the negative lookahead that asserts what follows is neither a comma or the end of the line (\d{3}(?!,|$))

$("#annual_sales").on('keyup', function() {
  $(this).val($(this).val().replace(/(\d{3}(?!,|1,"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />

2 of 7
2

Presumably, you want these commas added from the right as a US-style number separator. This code will do that by reversing before and after adding the commas.

var addCommas = s => s.split('').reverse().join('')
    .replace(/(\d{3})/g, '$1,').replace(/\,$/, '')
    .split('').reverse().join('')  // Really want String.prototype.revese!

$("#annual_sales").on('keyup', function () {
    $(this).val( addCommas($(this).val().replace(/\,/g, '')) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />

(Doing the reverses by converting to an array really makes me want a String.prototype.reverse method.)

If you have to support numbers with more than two decimal places, there would have to be additional work on this function.

Find elsewhere
🌐
GitHub
gist.github.com β€Ί 852326 β€Ί b74d36da699ed4b61472453ec31aa5141c0f49dd
Quick and dirty code to insert commas after every 3 digits (also handles decimals correctly) Β· GitHub
March 2, 2011 - How about this: function dirtyCommas(num) { return String(num).replace(/^\d+(?=.|$)/, function (int) { return int.replace(/(?=(?:\d{3})+$)(?!^)/g, ","); }); }
🌐
Yizhiyue
yizhiyue.me β€Ί 2019 β€Ί 04 β€Ί 09 β€Ί an-elegant-way-to-solve-adding-commas-between-every-3-digits-problem-in-javascript
An Elegant Way to Solve Adding Commas Between Every 3 Digits Problem in JavaScript | Zhiyue Β· ηΊΈε²³
April 9, 2019 - // If the index is a multiple of 3 and it's not the least digit, // that is the place we insert the comma behind. .reverse() // reverse back the array so that the digits are sorted in correctly display order .join("") ); // transform the array ...
🌐
JSFiddle
jsfiddle.net β€Ί jacobuid β€Ί ezbao2a3
Add Commas to Number - JSFiddle - Code Playground
JSFiddle - Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle.
🌐
DevGenius
blog.devgenius.io β€Ί how-to-format-a-number-with-commas-as-thousands-digit-separators-in-javascript-ce6ff8475192
How to Format a Number with Commas as Thousands Digit Separators in JavaScript? | by John Au-Yeung | Dev Genius
May 18, 2021 - In this article, we’ll take a look at how to format numbers with commas as thousands digit separators in JavaScript. We can use the replace method with a regex to add a comma every 3 digits.
🌐
Code Boxx
code-boxx.com β€Ί home β€Ί 3 ways to add comma to numbers in javascript (thousands separator)
3 Ways To Add Comma To Numbers In Javascript (Thousands Separator)
July 9, 2024 - But replace(/\B(?=(\d{3})+(?!\d))/g, ",") does the magic of inserting the commas. ... // (A) ADD COMMAS TO SEPERATE GIVEN NUMBER // num : original number // per : add comma per n digits (default 3) // places : number of decimal places (default ...
🌐
SitePoint
sitepoint.com β€Ί javascript
Comma separating numbers - JavaScript - SitePoint Forums | Web Development & Design Community
October 8, 2014 - I have a text field where user can input currency amount. When entering data , I want to add comma separating numbers into three digits without white spaces and if total digits are under three, then no comma added. E…
🌐
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
Top answer
1 of 16
3955

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 ====>"} ${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 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 ====>"} ${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.

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.

🌐
Stack Abuse
stackabuse.com β€Ί bytes β€Ί format-numbers-with-commas-in-javascript
Format Numbers with Commas in JavaScript
August 7, 2023 - function formatNumberWithCommas(number) ... 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....
🌐
HashBangCode
hashbangcode.com β€Ί article β€Ί format-numbers-commas-javascript
Format Numbers With Commas In JavaScript | #! code
The function works by using regular expressions to first split the string into whole number and decimal, before splitting the number by groups of three digits. The regular expression used is (\d+)(\d{3}), which looks for a sequence of three numbers preceded by any numbers.