🌐
JSFiddle
jsfiddle.net › dstorey › dNegX
Demo using the currency formatting style - JSFiddle - Code Playground
Console is avaialble for all users during beta, after that it'll be available for JSFiddle supporters.
🌐
Js
currency.js.org
currency.js
A small, lightweight javascript library for working with currency values.Download currency.js
🌐
Dinerojs
dinerojs.com
Dinero.js
Create, calculate, and format money in JavaScript and TypeScript.
🌐
Openexchangerates
openexchangerates.github.io › money.js
money.js / fx() - javascript currency conversion library
Read on for some background information, or jump straight to the downloads, demo playground or documentation. In order to perform currency conversion in JavaScript, you'll need a reliable source of real-time exchange rates.
🌐
GitHub
github.com › scurker › currency.js
GitHub - scurker/currency.js: A javascript library for handling currencies · GitHub
A javascript library for handling currencies. Contribute to scurker/currency.js development by creating an account on GitHub.
Starred by 3.4K users
Forked by 147 users
Languages   JavaScript 94.7% | TypeScript 5.3%
🌐
CodeSandbox
codesandbox.io › s › pdj7n
currency.js - CodeSandbox
February 15, 2021 - currency.js by alsantos123 using currency.js, react, react-dom, react-scripts
Published   Feb 14, 2021
Author   alsantos123
🌐
DEV Community
dev.to › ekeijl › intlnumberformat-playground-23gh
Format numbers in the user's locale using vanilla JS - DEV Community
November 24, 2023 - const formatter = new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }) console.log(formatter.format(123456.789)); // expected output: "123.456,79 €" The NumberFormat documentation on MDN is not very clear about the available options, so I decided to build a playground that allows you to customize the formatting options and immediately see the result for a list of locales and input numbers.
🌐
Netlify
vue-currency-input-v1.netlify.app › api
API | Vue Currency Input
Vue Currency Input · Guide · Config Reference · Playground · API · parse · getValue · setValue · Parses a currency formatted string emitted by the v-currency directive to a number. This method is also exposed as Vue instance method $ci.parse when installed as Vue plugin.
Find elsewhere
🌐
Numeraljs
numeraljs.com
Numeral.js
// load a locale numeral.register('locale', 'fr', { delimiters: { thousands: ' ', decimal: ',' }, abbreviations: { thousand: 'k', million: 'm', billion: 'b', trillion: 't' }, ordinal : function (number) { return number === 1 ? 'er' : 'ème'; }, currency: { symbol: '€' } }); // switch between locales numeral.locale('fr'); As I am not fluent in every locale on the planet, please feel free to create locale files of your own by submitting a pull request. Don't forget to create both the locale file (example: locales/fr.js) and the locale test (example: tests/locales/fr.js).
🌐
JSFiddle
jsfiddle.net › dstorey › GSrAt
Demo using the Japanese Yen currency - JSFiddle - Code Playground
Console is avaialble for all users during beta, after that it'll be available for JSFiddle supporters.
🌐
JSFiddle
jsfiddle.net › jinglesthula › hdzTy
Convert (Currency) String to Float - JSFiddle - Code Playground
We do and so much of JSFiddle was still dependant on it till this day, but since almost all MooTools features are now available in native JS it was high-time to strip it out of the codebase.
🌐
CodeSandbox
codesandbox.io › examples › package › @dinero.js › currencies
@dinero.js/currencies examples - CodeSandbox
Use this online @dinero.js/currencies playground to view and fork @dinero.js/currencies example apps and templates on CodeSandbox.
Top answer
1 of 16
2860

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>

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Intl › NumberFormat
Intl.NumberFormat - JavaScript - MDN Web Docs
js · const number = 123456.789; // request a currency format console.log( new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format( number, ), ); // 123.456,79 € // the Japanese yen doesn't use a minor unit console.log( new Intl.NumberFormat("ja-JP", { style: "currency", currency: "JPY" }).format( number, ), ); // ¥123,457 // limit to three significant digits console.log( new Intl.NumberFormat("en-IN", { maximumSignificantDigits: 3 }).format( number, ), ); // 1,23,000 // Formatting with units console.log( new Intl.NumberFormat("pt-PT", { style: "unit", unit: "kilometer-per-hour", }).format(50), ); // 50 km/h console.log( (16).toLocaleString("en-GB", { style: "unit", unit: "liter", unitDisplay: "long", }), ); // 16 litres ·
🌐
SoloLearn
sololearn.com › en › compiler-playground › cg30RleQUDm6
Python Playground - Currency Converter app: Online Interpreter, Compiler & Editor | Sololearn
Use our FREE Node.JS online compiler to write, run and share your code. Works directly from your browser without any additional installation.
🌐
JSFiddle
jsfiddle.net › mani04 › w6oo9b6j
Format input currency value - JSFiddle - Code Playground
Console is avaialble for all users during beta, after that it'll be available for JSFiddle supporters.
🌐
JSFiddle
jsfiddle.net › BumbleB2na › NfMQ7
HTML5 Input for Currency Format - JSFiddle - Code Playground
We do and so much of JSFiddle was still dependant on it till this day, but since almost all MooTools features are now available in native JS it was high-time to strip it out of the codebase.
🌐
JSFiddle
jsfiddle.net › trixta › UC6tG
Using type number for a currency input - JSFiddle - Code Playground
We do and so much of JSFiddle was still dependant on it till this day, but since almost all MooTools features are now available in native JS it was high-time to strip it out of the codebase.