(Math.round(num * 100) / 100).toFixed(2);

Live Demo

var num1 = "1";
document.getElementById('num1').innerHTML = (Math.round(num1 * 100) / 100).toFixed(2);

var num2 = "1.341";
document.getElementById('num2').innerHTML = (Math.round(num2 * 100) / 100).toFixed(2);

var num3 = "1.345";
document.getElementById('num3').innerHTML = (Math.round(num3 * 100) / 100).toFixed(2);
span {
    border: 1px solid #000;
    margin: 5px;
    padding: 5px;
}
<span id="num1"></span>
<span id="num2"></span>
<span id="num3"></span>

Note that it will round to 2 decimal places, so the input 1.346 will return 1.35.

Answer from jrn.ak on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Intl › NumberFormat › NumberFormat
Intl.NumberFormat() constructor - JavaScript | MDN
Indicates the increment at which rounding should take place relative to the calculated rounding magnitude. Possible values are 1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, and 5000; the default is 1. It cannot be mixed with significant-digits rounding or any setting of roundingPriority other than auto. ... How decimals should be rounded.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-format-a-number-with-two-decimals-in-javascript
How to Format a Number with Two Decimals in JavaScript? - GeeksforGeeks
July 23, 2025 - By multiplying the number by 100, rounding it, and then dividing by 100, we effectively round the number to two decimal places.
🌐
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 - One of the many things NumberFormat can help us with is with currencies. To get both the currency symbol and our decimals without the need for the template literal or hard coding, we can specify the style and currency parameters for the NumberFormat constructor:
🌐
CoreUI
coreui.io › blog › how-to-round-a-number-to-two-decimal-places-in-javascript
How to round a number to two decimal places in JavaScript · CoreUI
February 21, 2024 - This method rounds the number and formats it according to the specified locale, making it invaluable for international applications. ... The key to rounding to 2 decimal places is to manipulate the number such that the function applies rounding at the correct decimal position, as illustrated through the methods above. How do you round numbers in JavaScript without built-in methods?
🌐
Scurker
scurker.github.io › currency.js
currency.js
function format(currency, options) { return `${currency.dollars()}.${currency.cents()}`; } currency(1234.56, { format }).format(); // => "1234.56" Currency accepts decimal values (i.e. 1.23) with a default precision of 2, but can accept a minor currency unit (e.g.
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>

🌐
Codedamn
codedamn.com › news › javascript
JavaScript round a number to 2 decimal places (with examples)
December 11, 2022 - These are functions defined by the users themselves. here I have shown some examples below: Example of a user-defined function by using an exponent. It will round the number up and down. “e+2”, 2 is for 2 decimal places.
🌐
W3Schools
w3schools.com › howto › howto_js_format_number_dec.asp
How To Format a Number with Two Decimals
let num = 5.56789; let n = ... let n = num.toFixed(3); // 5.568 Try it Yourself » · Tip: Learn more about the toFixed() method in our JavaScript Reference....
Find elsewhere
Top answer
1 of 3
16

My solution uses successive .replace

  1. .replace(/(?!\.)\D/g, "") deletes all non numeric characters except .
  2. .replace(/(?<=\..*)\./g, "") removes all extra . except the first .
  3. .replace(/(?<=\.\d\d).*/g, "") deletes everything after 2 decimal places
  4. .replace(/\B(?=(\d{3})+(?!\d))/g, ",") inserts commas at appropriate places

I have modified the event to account for all changes to input field as .on('change click keyup input paste'

Snippet:

$('#price').on('change click keyup input paste',(function (event) {
    $(this).val(function (index, value) {
        return '$' + value.replace(/(?!\.)\D/g, "")
                          .replace(/(?<=\..*)\./g, "")
                          .replace(/(?<=\.\d\d).*/g, "")
                          .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    });
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="price" name="price" />

2 of 3
4

You can limit the keys in the keydown event instead of keyup and allow specific keys to take effect, and then format the input on keyup event:

$("#testinput").on("keydown", function(e) {
  var keycode = (event.which) ? event.which : event.keyCode;
  if (e.shiftKey == true || e.ctrlKey == true) return false;
  if ([8, 110, 39, 37, 46].indexOf(keycode) >= 0 || // allow tab, dot, left and right arrows, delete keys
    (keycode == 190 && this.value.indexOf('.') === -1) || // allow dot if not exists in the value
    (keycode == 110 && this.value.indexOf('.') === -1) || // allow dot if not exists in the value
    (keycode >= 48 && keycode <= 57) || // allow numbers
    (keycode >= 96 && keycode <= 105)) { // allow numpad numbers
    // check for the decimals after dot and prevent any digits
    var parts = this.value.split('.');
    if (parts.length > 1 && // has decimals
      parts[1].length >= 2 && // should limit this
      (
        (keycode >= 48 && keycode <= 57) || (keycode >= 96 && keycode <= 105)
      ) // requested key is a digit
    ) {
      return false;
    } else {
      if (keycode == 110) {
        this.value += ".";
        return false;
      }
      return true;
    }
  } else {
    return false;
  }
}).on("keyup", function() {
  var parts = this.value.split('.');
  parts[0] = parts[0].replace(/,/g, '').replace(/^0+/g, '');
  if (parts[0] == "") parts[0] = "0";
  var calculated = parts[0].replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
  if (parts.length >= 2) calculated += "." + parts[1].substring(0, 2);
  this.value = calculated;
  if (this.value == "NaN" || this.value == "") this.value = 0;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="testinput">

🌐
xjavascript
xjavascript.com › blog › how-to-format-numbers-as-currency-strings
How to Format Numbers as Currency Strings in JavaScript: Create a Function to Return '$ 2,500.00' — xjavascript.com
Currency Symbol: The dollar sign ($). Space: A single space between the symbol and the numeric value. Thousand Separators: Commas (,) to separate thousands (e.g., 2,500 instead of 2500). Decimal Places: Exactly two decimal places (.00), even for whole numbers. ... JavaScript’s Intl.NumberFormat API is the standard tool for formatting numbers (including currencies) across locales.
🌐
Chron.com
smallbusiness.chron.com › displaying-number-currency-javascript-33071.html
Displaying a Number as Currency in JavaScript
November 22, 2017 - Starting with a number such as ... 456.7800 by appending two decimal places at the end of the number. The accounting.formatMoney() method uses the accounting library in JavaScript to convert a number to its equivalent in a ...
🌐
Delft Stack
delftstack.com › home › howto › javascript › javascript round to 2 decimal places
How to Round a Number to 2 Decimal Places in JavaScript | Delft Stack
March 11, 2025 - The Math.round() function then rounds the result to the nearest whole number. Finally, we divide by 100 to shift the decimal point back to its original position. This method effectively rounds the number to two decimal places while keeping it ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Number › toFixed
Number.prototype.toFixed() - JavaScript | MDN
The toFixed() method of Number values returns a string representing this number using fixed-point notation with the specified number of decimal places. function financial(x) { return Number.parseFloat(x).toFixed(2); } console.log(financial(123.456)); // Expected output: "123.46" console.lo...
🌐
W3docs
w3docs.com › javascript
How to Format a Number with Two Decimals in JavaScript
const format = (num, decimals) => num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2, }); console.log(format(3.005)); // "3.01" console.log(format(2.345)); // "2.35"
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Intl › NumberFormat
Intl.NumberFormat - JavaScript | MDN
Chinese decimal console.log(new Intl.NumberFormat("zh-Hans-CN-u-nu-hanidec").format(number)); // 一二三,四五六.七八九 // when requesting a language that may not be supported, such as // Balinese, include a fallback language, in this case Indonesian console.log(new Intl.NumberFormat(["ban", "id"]).format(number)); // 123.456,789 · The results can be customized using the options argument: ... 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
🌐
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 - Different locales and currencies ... component library. For simple cases without locale requirements, use toFixed(2) with manual symbol addition....
🌐
Openexchangerates
openexchangerates.github.io › accounting.js
accounting.js: JavaScript number and currency formatting library
// Settings object that controls ... ",", decimal : "." } } // These can be changed externally to edit the library's defaults: accounting.settings.currency.format = "%s %v"; // Format can be an object, with `pos`, `neg` and `zero`: accounting.settings.currency.format = { ...
🌐
Zapier
community.zapier.com › featured-articles-65 › how-to-format-currency-numbers-with-consistent-padding-for-decimal-places-11918
How to format currency numbers with consistent padding for decimal places | Zapier Community
October 13, 2021 - It simply needs to be pasted into ... these names: // - amount (the number to be formatted) // - decimalPlaces (the number of decimal places to keep/create for the // output) // - locale (ex: 'en-US' or 'de-DE'....