After trying many different solutions, this seems (to me) the best way:

JS Fiddle demo

(1234568).toLocaleString("en-US", {style: "decimal", minimumFractionDigits: 2});

or

var opts = '{style: "decimal", currency: "USD", minimumFractionDigits: 2}';
(1234568).toLocaleString("en-US", opts);

or

(1234568).toLocaleString("en-US", {style: "decimal", minimumFractionDigits: 0});

I liked NickG's comment from mid-2013: "Agreed, it's not fully supported across all browsers (yet), but it's still a solution. (And arguably the most valid solution, as its forward compatible with the non-supported browsers, and it's a documented feature of the JavaScript api.)"

Sources:

How to format numbers as currency strings

How to format a number with commas as thousands separators?

Answer from crashwap on Stack Overflow
🌐
freeCodeCamp
freecodecamp.org › news › how-to-format-number-as-currency-in-javascript-one-line-of-code
How to Format a Number as Currency in JavaScript
November 7, 2024 - For example, 14340 would be $14,340.00 ... and style. And you can convert these numbers into currencies using the Intl.NumberFormat() method in JavaScript......
🌐
Codedamn
codedamn.com › news › javascript
How to Format a Number as Currency in JavaScript
June 3, 2023 - In this example, we created a ... as arguments. The function uses regular expressions to add commas as thousands separators and then returns the formatted currency string using a template literal....
Top answer
1 of 3
9

After trying many different solutions, this seems (to me) the best way:

JS Fiddle demo

(1234568).toLocaleString("en-US", {style: "decimal", minimumFractionDigits: 2});

or

var opts = '{style: "decimal", currency: "USD", minimumFractionDigits: 2}';
(1234568).toLocaleString("en-US", opts);

or

(1234568).toLocaleString("en-US", {style: "decimal", minimumFractionDigits: 0});

I liked NickG's comment from mid-2013: "Agreed, it's not fully supported across all browsers (yet), but it's still a solution. (And arguably the most valid solution, as its forward compatible with the non-supported browsers, and it's a documented feature of the JavaScript api.)"

Sources:

How to format numbers as currency strings

How to format a number with commas as thousands separators?

2 of 3
2

You could have provided some inputs and corresponding outputs to describe your problem clearer. I assume you need a function that gets as input any non-negative number and want as output a string formatted with decimal point and thousand-separators. If my assumption is true the following might help you, tested on firefox 24.0 /Linux:

<!DOCTYPE html>
<html>
<head>
    <title>HTML</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
        var decimalSeparator = ".";
        var decimalDefault = decimalSeparator + "00";
        var thousandsSeparator = ",";

        /**
         * @param {String or Number} value The value to format
         * @returns {String} The formatted Number as a String
         */
        function formatMoney(value) {
            var valueStr = String(value);
            var decimalDividerPos = valueStr.indexOf(".");
            var decimalPart = decimalDividerPos == -1 ? decimalDefault : decimalSeparator + valueStr.substr(decimalDividerPos + 1);
            var integerPart = decimalDividerPos == -1 ? valueStr : valueStr.substring(0, decimalDividerPos);
            var integerAry = new Array();
            var lenTemp = 0;
            for (var i = integerPart.length - 1; i >= 0; i--) {
                integerAry.unshift(integerPart.substr(i, 1));
                if (i && (!(++lenTemp % 3))) {
                    integerAry.unshift(thousandsSeparator);
                }
            }
            return integerAry.join("") + decimalPart;
        }
    </script>
<body>
    <script type="text/javascript">
        var testValues = new Array(
                0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000,
                0.9876, 1.9876, 10.9876, 100.9876, 1000.9876, 10000.9876, 100000.9876, 1000000.9876, 10000000.9876,
                1234567e+123, Number.MAX_VALUE);
        for (var x in testValues) {
            console.log("VALUE=" + testValues[x] + " =>  FORMATTED=" + formatMoney(testValues[x]));
        }
    </script>
</body>
</html>
🌐
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.
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.

🌐
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....
Find elsewhere
🌐
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 - ... The NumberFormat() object is used to represent numbers in a language-sensitive formatting. It can be used to represent currency or percentages according to the locale specified.
🌐
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 - P.S. I have another tutorial to format the number as a currency, link below. ... // CREDIT: https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript // (A) THE NUMBER var num = 1234567.89; // (B) CONVERT TO STRING & REPLACE var commas = num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); console.log(commas); // 1,234,567.89
🌐
CodePen
codepen.io › 559wade › pen › LRzEjj
Currency Format Input Field
<div class="main"> <h1>Auto Formatting Currency</h1> <form method="post" action="#"> <label for="currency-field">Enter Amount</label> <input type="text" name="currency-field" id="currency-field" pattern="^\$\d{1,3}(,\d{3})*(\.\d+)?$" value="" data-type="currency" placeholder="$1,000,000.00"> <button type="submit">Submit</button> </form> <p>Auto format currency input field with commas and decimals if needed.
🌐
DZone
dzone.com › coding › javascript › how to format a number as currency in javascript
How to Format a Number as Currency in JavaScript
February 7, 2023 - When no locale or option is given to the Intl.NumberFormat() constructor will simply format the integer by adding commas. const price = 17225; console.log(new Intl.NumberFormat().format(price)); ... As noted above, you are not looking for standard ...
🌐
EnableGeek
enablegeek.com › home › format string as currency in javascript
Format String as Currency in Javascript - EnableGeek
March 25, 2024 - This will format the number as a currency string with the dollar sign and commas as the thousand separator. You can use the ‘Intl.NumberFormat()’ method to format numbers as currency strings in JavaScript.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Number › toLocaleString
Number.prototype.toLocaleString() - 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(number.toLocaleString("de-DE")); // 123.456,789 // Arabic in most Arabic speaking countries uses Eastern Arabic digits console.log(number.toLocaleString("ar-EG")); // ١٢٣٤٥٦٫٧٨٩ // India uses thousands/lakh/crore separators console.log(number.toLocaleString("en-IN")); // 1,23,456.789 // the nu extension key requests a numbering system, e.g.
🌐
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 - 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 number as currency with commas:
Top answer
1 of 16
2859

Intl.NumberFormat

JavaScript has a number formatter (part of the Internationalization API).

// Create our number formatter.
const formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',

  // These options can be used to round to whole numbers.
  trailingZeroDisplay: 'stripIfInteger'   // This is probably what most people
                                          // want. It will only stop printing
                                          // the fraction when the input
                                          // amount is a round number (int)
                                          // already. If that's not what you
                                          // need, have a look at the options
                                          // below.
  //minimumFractionDigits: 0, // This suffices for whole numbers, but will
                              // print 2500.10 as $2,500.1
  //maximumFractionDigits: 0, // Causes 2500.99 to be printed as $2,501
});

// Use the formatter with the value of an input.
let input = document.getElementById('amount');
input.addEventListener('keyup', e => {
    document.getElementById('result').innerText = formatter.format(e.target.value);
});
input.dispatchEvent(new Event('keyup'));
<label>
    Amount
    <input id="amount" value="2500">
</label>
Result:
<span id="result"></span>

Use undefined in place of the first argument ('en-US' in the example) to use the system locale (the user locale in case the code is running in a browser). Further explanation of the locale code.

Here's a list of the currency codes.

Intl.NumberFormat vs Number.prototype.toLocaleString

A final note comparing this to the older .toLocaleString. They both offer essentially the same functionality. However, toLocaleString in its older incarnations (pre-Intl) does not actually support locales: it uses the system locale. So when debugging old browsers, be sure that you're using the correct version (MDN suggests to check for the existence of Intl). There isn't any need to worry about this at all if you don't care about old browsers or just use the shim.

Also, the performance of both is the same for a single item, but if you have a lot of numbers to format, using Intl.NumberFormat is ~70 times faster. Therefore, it's usually best to use Intl.NumberFormat and instantiate only once per page load. Anyway, here's the equivalent usage of toLocaleString:

console.log((2500).toLocaleString('en-US', {
  style: 'currency',
  currency: 'USD',
})); /* $2,500.00 */

Some notes on browser support and Node.js

  • Browser support is no longer an issue nowadays with 99+% support globally
  • There is a shim to support it on fossilized browsers (like Internet Explorer 8), should you really need to
  • Node.js before v13 only supports en-US out of the box. One solution is to install full-icu, see here for more information
  • Have a look at CanIUse for more information
2 of 16
1973

Number.prototype.toFixed

This solution is compatible with every single major browser:

  const profits = 2489.8237;

  profits.toFixed(3) // Returns 2489.824 (rounds up)
  profits.toFixed(2) // Returns 2489.82
  profits.toFixed(7) // Returns 2489.8237000 (pads the decimals)

All you need is to add the currency symbol (e.g. "$" + profits.toFixed(2)) and you will have your amount in dollars.

Custom function

If you require the use of , between each digit, you can use this function:

function formatMoney(number, decPlaces, decSep, thouSep) {
    decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
    decSep = typeof decSep === "undefined" ? "." : decSep;
    thouSep = typeof thouSep === "undefined" ? "," : thouSep;
    var sign = number < 0 ? "-" : "";
    var i = String(parseInt(number = Math.abs(Number(number) || 0).toFixed(decPlaces)));
    var j = (j = i.length) > 3 ? j % 3 : 0;

    return sign +
        (j ? i.substr(0, j) + thouSep : "") +
        i.substr(j).replace(/(\decSep{3})(?=\decSep)/g, "$1" + thouSep) +
        (decPlaces ? decSep + Math.abs(number - i).toFixed(decPlaces).slice(2) : "");
}

document.getElementById("b").addEventListener("click", event => {
  document.getElementById("x").innerText = "Result was: " + formatMoney(document.getElementById("d").value);
});
<label>Insert your amount: <input id="d" type="text" placeholder="Cash amount" /></label>
<br />
<button id="b">Get Output</button>
<p id="x">(press button to get output)</p>

Use it like so:

(123456789.12345).formatMoney(2, ".", ",");

If you're always going to use '.' and ',', you can leave them off your method call, and the method will default them for you.

(123456789.12345).formatMoney(2);

If your culture has the two symbols flipped (i.e., Europeans) and you would like to use the defaults, just paste over the following two lines in the formatMoney method:

    d = d == undefined ? "," : d,
    t = t == undefined ? "." : t,

Custom function (ES6)

If you can use modern ECMAScript syntax (i.e., through Babel), you can use this simpler function instead:

function formatMoney(amount, decimalCount = 2, decimal = ".", thousands = ",") {
  try {
    decimalCount = Math.abs(decimalCount);
    decimalCount = isNaN(decimalCount) ? 2 : decimalCount;

    const negativeSign = amount < 0 ? "-" : "";

    let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString();
    let j = (i.length > 3) ? i.length % 3 : 0;

    return negativeSign +
      (j ? i.substr(0, j) + thousands : '') +
      i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) +
      (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : "");
  } catch (e) {
    console.log(e)
  }
};

document.getElementById("b").addEventListener("click", event => {
  document.getElementById("x").innerText = "Result was: " + formatMoney(document.getElementById("d").value);
});
<label>Insert your amount: <input id="d" type="text" placeholder="Cash amount" /></label>
<br />
<button id="b">Get Output</button>
<p id="x">(press button to get output)</p>

🌐
DEV Community
dev.to › schalkneethling › number-and-currency-formatting-in-javascript-using-intlnumberformat-46og
Number and Currency Formatting in JavaScript using Intl.NumberFormat - DEV Community
April 3, 2024 - With this, the numbers will now be formatted as follows: ... The numbers we are printing are monetary values so they are missing a decimal value and a currency symbol. One way we can do this is by using JavaScript template literals to append and prepend the pieces we are missing.
🌐
Favtutor
favtutor.com › articles › format-numbers-commas-javascript
Format Numbers with Commas in JavaScript (with code)
February 5, 2024 - In this article, we will learn different methods to format numbers by adding commas in JavaScript and making our numbers more user-friendly on a webpage. When we are displaying numbers on a webpage, we have to make sure that they are easy to read. Whether we are dealing with currency values, ...