🌐
JSON
json.org
JSON
An array is an ordered collection of values. An array begins with [left bracket and ends with ]right bracket. Values are separated by ,comma. A value can be a string in double quotes, or a number, or true or false or null, or an object or an array.
text-based open standard designed for human-readable data interchange
whitespace
object
combox respuesta json
JSON (JavaScript Object Notation, pronounced /ˈdʒeɪsən/ or /ˈdʒeɪˌsɒn/) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of name–value pairs … Wikipedia
Factsheet
JavaScript Object Notation
Filename extension .json
Internet media type application/json
Factsheet
JavaScript Object Notation
Filename extension .json
Internet media type application/json
🌐
Plotly
community.plotly.com › plotly.js
Replacing thousand separator "k" with comma - plotly.js - Plotly Community Forum
January 8, 2019 - In the below image, is it possible to remove the “k” following the numbers in the hover text and/or the y-axis and replace it with the number and a comma? For example, 81.014k → 81,014. Here’s an example of my trace code: var trace3 = { type: "scatter", mode: "lines", name: 'Massachusetts', x: unpack(rows, 'year'), y: unpack(rows, 'MA_adm'), line: { dash: 'solid', color: colors[2] } }
Discussions

How to Display Numbers with a Comma Separator
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 ... More on forum.wixstudio.com
🌐 forum.wixstudio.com
0
September 26, 2019
javascript - How can I format a number with commas as thousands separators? - Stack Overflow
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 ... 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
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
🌐
Jonkuperman
jonkuperman.com › javascript-format-number
JavaScript format number
The first thing we can try is using Regular Expressions. We can take any number, cast it to a string and then use the replace() method to add add a comma or decmial after every group of 3 numbers.
🌐
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.

🌐
DataTables
datatables.net › plug-ins › sorting › numeric-comma
Commas for decimal place
Sort numbers correctly which use a comma as the decimal place.
🌐
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...
Find elsewhere
🌐
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.
🌐
Elisabethirgens
elisabethirgens.github.io › notes › 2020 › 03 › format-numbers
Format Numbers With Intl.NumberFormat
March 26, 2020 - Intl.NumberFormat({ minimumFractionDigits: 2 }).format(5000.0); // returns "5,000" option is completely ignored Intl.NumberFormat("en-US", { minimumFractionDigits: 2 }).format(5000.0); // returns "5,000.00" added zeros iz back :-) Butbutbut I want this result without specifying the locale… Tried some versions with a space before the comma separating the options (SyntaxError!) empty strings with single quotes or double quotes (RangeError!).
🌐
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.
🌐
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.
🌐
Prettier
prettier.io › docs › configuration
Configuration File · Prettier
The configuration file will be resolved starting from the location of the file being formatted, and searching up the file tree until a config file is (or isn’t) found.
🌐
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.