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
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Intl › NumberFormat
Intl.NumberFormat - JavaScript | MDN
Getter function that formats a range of numbers according to the locale and formatting options of the Intl.NumberFormat object from which the method is called.
🌐
DEV Community
dev.to › ivan_kaminskyi › formatting-prices-in-javascript-5h1g
Formatting Prices in JavaScript - DEV Community
August 5, 2024 - To format a price in JavaScript, you can use the toFixed method of the Number object. The toFixed method returns a string representing the number in fixed-point notation. The toFixed method takes an optional parameter that specifies the number ...
🌐
Scurker
scurker.github.io › currency.js
currency.js
currency.js was built to work around common floating point issues in javascript with a flexible api.
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>

🌐
CoreUI
coreui.io › answers › how-to-format-a-number-as-currency-in-javascript
How to format a number as currency in JavaScript · CoreUI
September 27, 2025 - Use Intl.NumberFormat to format numbers as currency with proper locale and symbol handling in JavaScript.
🌐
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 - let pounds = Intl.NumberFormat('en-GB', { style: 'currency', currency: 'GBP', maximumSignificantDigits: 3, }); console.log(`Pounds: ${pounds.format(price)}`); // Pounds: £143,000 · I hope this article was worth your time. You now know how to format a number as currency with JavaScript without relying on any external library.
🌐
Reddit
reddit.com › r/reactjs › how to handle prices/currency formatting in javascript?
r/reactjs on Reddit: How to handle prices/currency formatting in Javascript?
February 25, 2021 -

When I try to add the total of the items (being fetched from an API), I am currently returning a string. When I try to convert it to a number, the formatting is off for USD.

For example, how can I convert a string of a number such as "131.40" to the number 131.40, or "14.1" to the number 14.10?

I understand that the biggest issue has to do with the numbers being floating point math. But I'm unclear on how to handle this problem. Do I convert the way my prices are being currently displayed? Any advice appreciated.

Here is the full context of my code:

const products = [{
  id: 1,
  price: 109.1,
  quantity: 1,
  title: "T-Shirt"
}, 
{
  id: 2,
  price: 22.3,
  quantity: 1,
  title: "Jeans"
}]

function totalPrice(storageItems){
      const totalPriceHolder = []
      storageItems.map((a, index) => {
       const totalPrice = a.price * a.quantity;
    totalPriceHolder.push((totalPrice))
  })

console.log("Check1", totalPriceHolder)

   const totalPriceReduce = totalPriceHolder.reduce((a, b) => a + b, 0).toFixed(2);
   console.log("Check 2", totalPriceReduce)
   return parseFloat(totalPriceReduce)
}

console.log(totalPrice(products))
Top answer
1 of 5
8
You have two concerns you need to handle: Monetary calculation Currency formatting Monetary calculations in Javascript are tricky because of the way the numerical standard IEEE 754 works. To avoid incorrect final figures you want to work in cents. You will convert your decimal to cents by multiplying by 100, do all your calculations and then convert back by dividing by 100. You want to output your result in the ideal format for your user. You should use the Intl api for this. It will handle formatting in the conventional way for a given currency and country. As long as you're working with USD it's not a big concern, though it is a useful API, but it's good practice to use it as it will make it easier to handle other currencies later which can be non trivial. For example, Ireland and Germany both use EUR but would display monetary values differently. I wouldn't go anywhere near the toFixed API.
2 of 5
3
This doesn't perform the conversions, but there is a method that formats different currencies automatically called new Intl.NumberFormat(). I'll demonstrate with an example of two sample users with different locations and currencies set: const USER_USA = { name: "some guy", currency: 'USD', locale: 'en-US', transactionAmount: 7.1346131234 }; const USER_GB = { name: "some other guy", currency: 'GBP', locale: 'en-GB', transactionAmount: 21.124361341234 }; const calcCurrency = function(locale, currency, amount) { return new Intl.NumberFormat(locale, { style: 'currency', currency: currency }).format(amount); }; let activeAccount = USER_USA; console.log(calcCurrency( activeAccount.locale, activeAccount.currency, activeAccount.transactionAmount )); // Yields: "$7.13" (Yes, it even rounds it and always displays only two decimal points) activeAccount = USER_GB; console.log(calcCurrency( activeAccount.locale, activeAccount.currency, activeAccount.transactionAmount )); // Yields: "£21.12" You can literally just copy this code and it works as is, but experiment with it. Creating a function that does all this formatting for you is great.
Find elsewhere
🌐
Price-format
price-format.github.io › Jquery-Price-Format
Jquery-price-format by flaviosilveira
jQuery Price Format Plugin is useful to format input fields and HTML elements as prices.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Intl › NumberFormat › NumberFormat
Intl.NumberFormat() constructor - JavaScript | MDN
Possible values are from 0 to 100; the default for plain number formatting is the larger of minimumFractionDigits and 3; the default for currency formatting is the larger of minimumFractionDigits and the number of minor unit digits provided by the ISO 4217 currency code list (2 if the list doesn't provide that information); the default for percent formatting is the larger of minimumFractionDigits and 0.
🌐
npm
npmjs.com › package › format-money-js
format-money-js - npm
const fm = new FormatMoney({ symbol: '$' }); console.log(fm.from(12345.67, { symbol: '€' })); // €12,345.67 console.log(fm.un('€12.345,67', { decimalPoint: ',' })); // 12345.67
      » npm install format-money-js
    
Published   Feb 27, 2023
Version   1.6.3
Author   @dejurin
🌐
Vultr Docs
docs.vultr.com › javascript › examples › format-numbers-as-currency-strings
JavaScript Program to Format Numbers as Currency Strings | Vultr Docs
December 20, 2024 - This code snippet formats an array of numbers into GBP currency strings. The resulting array formattedPrices contains values like £99.99, £2,500.00, and £150.75. Handle user input for a price.
🌐
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.
🌐
Stack Abuse
stackabuse.com › how-to-format-number-as-currency-string-in-javascript
How to Format Number as Currency String in JavaScript
February 27, 2023 - const price = 1470000.15; // Format the price above to USD, INR, EUR using their locales.
🌐
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 - For example, 17225 would be $17,225.00 (US Dollars), 17,225.00 (Rupees), or €17,225,00 (Euros), depending on your chosen currency, location, and style. You may also use JavaScript's Intl.NumberFormat() ...
🌐
TutorialsPoint
tutorialspoint.com › How-can-I-format-numbers-as-dollars-currency-string-in-JavaScript
How can I format numbers as dollars currency string in JavaScript?
let price = 1642; var currencyUSD = ‘$’ + price; The below example demonstrates how users can add the ‘$’ sign to the number using the string concatenation in JavaScript. <!DOCTYPE html> <html> <body> <h2>Format Numbers as a dollar currency string</h2> <p> Formatting 1642 as US dollars (US$):</p> <p id="result"> </p> <script type="text/javascript"> // function to format number with $ sign.
🌐
Openexchangerates
openexchangerates.github.io › accounting.js
accounting.js: JavaScript number and currency formatting library
Enter any number into the box and choose currency. Uses accounting.formatMoney(): ... <script src="path/to/accounting.js"></script> <script type="text/javascript"> // Library ready to use: accounting.formatMoney(5318008); </script>
🌐
Koladechris
koladechris.com › blog › how-to-format-currencies-in-javascript
JavaScript Format Number as Currency – How to Format Currencies in JavaScript
That solution is the Intl.NumberFormat object of the JavaScript Internationalization API. ... Subscribe to my newsletter for coding tips, videos from reputable sources, articles from OG tech authors, and a ton of other goodies. No BS. No fluff. Just pure software development goodies on a Sunday every week. Now unto how to format currencies with the Intl.NumberFormat object…
🌐
SamanthaMing
samanthaming.com › tidbits › 30-how-to-format-currency-in-es6
How to Format Currency in ES6 | SamanthaMing.com
const money = 💰; // Old Way money.toLocaleString('en-US', {style: 'currency', currency: 'USD'} ); // '$100.00' // ✅ ES6 Way new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' } ).format(money); // '$100.00'