When you use Number.toFixed() you obtain a string (not a number any more). For that reason, subsequent calls to .toLocaleString() launch the generic Object.toLocaleString() method that knows nothing about numbers, instead of the Number.toLocaleString() you want.

Having a look at the documentation we can compose something like this:

> Number(213245).toLocaleString("es-ES", {minimumFractionDigits: 2});
"213.245,00"

console.log(Number(213245).toLocaleString("es-ES", {minimumFractionDigits: 2}));

This is a relatively new addition so make sure to verify browser support, but it's been working in Firefox and Chrome-like browsers for a few years now. In particular, some runtimes like Node.js do not include the full ICU dataset by default.

Answer from Álvaro González on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Intl › NumberFormat
Intl.NumberFormat - JavaScript - MDN Web Docs
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)); ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Number › toLocaleString
Number.prototype.toLocaleString() - JavaScript | MDN
const number = 123456.789; // request ... digits console.log(number.toLocaleString("en-IN", { maximumSignificantDigits: 3 })); // 1,23,000 // Use the host default language with options for number formatting const num = 30000.65; console.log( num.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2, }), ); // "30,000.65" where English is the default language, or // "30.000,65" where German is the default ...
Discussions

javascript - How to format numbers by prepending 0 to single-digit numbers? - Stack Overflow
I want to format a number to have two digits. The problem is caused when 0–9 is passed, so I need it to be formatted to 00–09. Is there a number formatter in JavaScript? More on stackoverflow.com
🌐 stackoverflow.com
javascript - Format number to always show 2 decimal places - Stack Overflow
I would like to format my numbers to always display 2 decimal places, rounding where applicable. Examples: number display ------ ------- 1 1.00 1.341 1.34 1.345 1.35 I ... More on stackoverflow.com
🌐 stackoverflow.com
javascript - Number to german decimal format converter function - Code Review Stack Exchange
I have a function that formats ... to a German decimal format. I got this function from here https://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript and it works. But every time I want to format a number that I stored in a variable I have to add .format(2, 3, '.', ... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
October 14, 2015
numbers - Is there a functionality in JavaScript to convert values into specific locale formats? - Stack Overflow
Is there a built in function of JavaScript to convert a string into a particular locale (Euro in my case)? E.g. 50.00 should get converted to 50,00 €. More on stackoverflow.com
🌐 stackoverflow.com
🌐
DEV Community
dev.to › orimdominic › formatting-numbers-in-javascript-with-intl-numberformat-5goo
Formatting Numbers in JavaScript with Intl.NumberFormat - DEV Community
August 24, 2024 - A number like 123456 will be displayed in Spanish as 123.456, in English as 123,456 and in the Indian numerical system as 1,23,456. localesis a code in the form of a string that informs formatterObject of which language to use when formatting. You can find a list of the locales under subtag here. Examples are 'hi' for Hindi, 'de-AT' for German (de) used in Austria (AT) and 'en-IN' for English (en) used in India (IN).
Top answer
1 of 16
833

Edit (2021):

It's no longer necessary to format numbers by hand like this anymore. This answer was written way-back-when in the distant year of 2011 when IE was important and babel and bundlers were just a wonderful, hopeful dream.

I think it would be a mistake to delete this answer; however in case you find yourself here, I would like to kindly direct your attention to the second highest voted answer to this question as of this edit.

It will introduce you to the use of .toLocaleString() with the options parameter of {minimumIntegerDigits: 2}. Exciting stuff. Below I've recreated all three examples from my original answer using this method for your convenience.

[7, 7.5, -7.2345].forEach(myNumber => {
  let formattedNumber = myNumber.toLocaleString('en-US', {
    minimumIntegerDigits: 2,
    useGrouping: false
  })
  console.log(
    'Input:    ' + myNumber + '\n' +
    'Output:   ' + formattedNumber
  )
})


Original Answer:

The best method I've found is something like the following:

(Note that this simple version only works for positive integers)

var myNumber = 7;
var formattedNumber = ("0" + myNumber).slice(-2);
console.log(formattedNumber);

For decimals, you could use this code (it's a bit sloppy though).

var myNumber = 7.5;
var dec = myNumber - Math.floor(myNumber);
myNumber = myNumber - dec;
var formattedNumber = ("0" + myNumber).slice(-2) + dec.toString().substr(1);
console.log(formattedNumber);

Lastly, if you're having to deal with the possibility of negative numbers, it's best to store the sign, apply the formatting to the absolute value of the number, and reapply the sign after the fact. Note that this method doesn't restrict the number to 2 total digits. Instead it only restricts the number to the left of the decimal (the integer part). (The line that determines the sign was found here).

var myNumber = -7.2345;
var sign = myNumber?myNumber<0?-1:1:0;
myNumber = myNumber * sign + ''; // poor man's absolute value
var dec = myNumber.match(/\.\d+$/);
var int = myNumber.match(/^[^\.]+/);

var formattedNumber = (sign < 0 ? '-' : '') + ("0" + int).slice(-2) + (dec !== null ? dec : '');
console.log(formattedNumber);

2 of 16
273

Use the toLocaleString() method in any number. So for the number 6, as seen below, you can get the desired results.

(6).toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false})

Will generate the string '06'.

🌐
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" ... let num1 = 6.8; let num2 = 264.1364; ...
Top answer
1 of 2
3

For formatting currency, given that there are many desired formats, the easiest and most readable way is to just make a function called formatCurrency() that might look something like this:

function formatCurrency(amount, symbol, groupDigits, preFixed, exchangeCommas){
    var result = amount.toFixed(2);
    if(groupDigits){
        result = result.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
    }
    if(prefixed){
        result = symbol + result;
    }else{
        result = result + symbol;
    }
    if(exchangeCommas){
        var decimalIndex = result.lastIndexOf(".");
        result = result.replace(",", ".");
        result = result.substring(0, decimalIndex) + "," + result.substring(decimalIndex + 1);
    }
    return result;
}

https://stackoverflow.com/questions/14467433/currency-formatting-in-javascript

Edit: Note that the parameters groupDigits, preFixed and exchangeCommas are optional boolean values.

Then if you want to make it shorter or less readable for whatever reason there are online tools that make it easy to do so, such as yui compressor.

2 of 2
1

My suggestion is:

/**
 * Formats given number according to given options.
 * @param {number} number The number to be formatted.
 * @param {!Object.<string, *>} options The formatting options.
 * @return {string} The formatted number string.
 */
function formatNumber(number, options) {
  /** @type {Array.<string>} */
  var result = (options['fraction'] ? number.toFixed(options['fraction']) :
                                      '' + number).split('.');
  return options['prefix'] +
      result[0].replace(/\B(?=(\d{3})+(?!\d))/g,
      /** @type {string} */ (options['grouping'])) +
      (result[1] ? options['decimal'] + result[1] : '') +
      options['suffix'];
}

// Example:
var expected = '45.122,90 €';
var number = 45122.9;
var formatted = formatNumber(number, {
  'decimal': ',',
  'grouping': '.',
  'fraction': 2,
  'prefix': '',
  'suffix': ' €'
 });


alert('Formatted: ' + formatted + '\n' +
      'Expected: ' + expected + '\n' +
      'Equals: ' + (formatted == expected));

Source: https://github.com/Datamart/Glize/blob/master/src/formatters/NumberFormatter.js#L22

Find elsewhere
🌐
W3Schools
w3schools.com › howto › howto_js_format_number_dec.asp
How To Format a Number with Two Decimals
You can use the toFixed() method to format a number to only show two decimals. Note that the result is rounded (shows 5.57 instead of 5.56): let num = 5.56789; let n = num.toFixed(2); // 5.57 Try it Yourself » · If you want to display three ...
🌐
FreeFormatter
freeformatter.com › germany-standards-code-snippets.html
Formatting standards & code snippets for Germany - Freeformatter.com
Locale locale = new Locale("de", ... DateTime.Now.ToString("yyyy-MM-dd", ci); // or dd.MM.yyyy · let date = new Date(); date.toLocaleDateString('de-DE', {year: 'numeric', month: '2-digit', day:'2-digit'}); // in order to get yyyy-MM-dd format, use date.toISOString().substring(0, ...
🌐
SimpleLocalize
simplelocalize.io › blog › posts › number-formatting-in-javascript
Number formatting in JavaScript | SimpleLocalize
April 12, 2022 - const price = 30000.65; ... ... In this article, we go through every style. Use style property in options object with value currency to format number into a string....
🌐
javaspring
javaspring.net › blog › how-to-use-tolocalestring-and-tofixed-2-in-javascript
How to Use `toLocaleString()` and `toFixed(2)` in JavaScript: Format Numbers with Commas and 2 Decimal Places — javaspring.net
If your number is an integer (e.g., 9876), toLocaleString() will pad with zeros to meet minimumFractionDigits: 2: const integer = 9876; const formatted = integer.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); ...
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-format-number-to-two-decimal-places
Format a number to 2 Decimal places in JavaScript | bobbyhadz
Use the toFixed() method to format a number to 2 decimal places, e.g. num.toFixed(2). The toFixed method takes a parameter, representing how many digits should appear after the decimal and returns the result.
🌐
TestMu AI Community
community.testmu.ai › ask a question
JavaScript: Format Number to 2 Decimal Places - TestMu AI Community
October 22, 2024 - How can I format a number in JavaScript to always show 2 decimal places, rounding where applicable? For example, I want to achieve the following: number display 1 1.00 1.341 1.34 1.345 1.35 …
🌐
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 - In this approach we are using the toPrecision() method. This method formats a number to a specified precision (total number of significant digits).
🌐
Coderanch
coderanch.com › t › 113697 › languages › Number-Conversion-German-Format
Number Conversion to German Format!! (HTML Pages with CSS and JavaScript forum at Coderanch)
Hello Axel Janssen, My value is 1423234 German number: 1.423.234 I want to convert my value to German number in JavaScript...are there any functions for the same. Regards, Ravi :roll: ... Hello Christian Baron, I wish your code will work perfectly right...Thanks a lot. Regards, Ravi ... Hello Christian Baron, I had made small changes in ur code which goes here. function format( number ) { var n = ""+number; var s;//add by Ravi // make it a Stringvar s = 0; if( n.indexOf("-") > -1 ) s=1; // negative ?
🌐
W3Schools
w3schools.com › jsref › jsref_tolocalestring_number.asp
JavaScript Number toLocaleString() Method
The toLocaleString() returns a number as a string, using local language format.
Top answer
1 of 15
11

Here are some solutions and all pass the test suite. The test suite and benchmark are included. If you want copy and paste to test, try this gist.

Method 0 (RegExp)

It is based on VisioN's answer, but it fixes if there isn't a decimal point.

if (typeof Number.prototype.format === 'undefined') {
    Number.prototype.format = function (precision = 2) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.');
        a[0] = a[0].replace(/\d(?=(\d{3})+$)/g, '$&,');
        return a.join('.');
    }
}

console.log((-123456789.0134).format());

Method 1

if (typeof Number.prototype.format === 'undefined') {
    Number.prototype.format = function (precision = 2) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.'),
            // Skip the '-' sign
            head = Number(this < 0);

        // Skip the digits that's before the first thousands separator
        head += (a[0].length - head) % 3 || 3;

        a[0] = a[0].slice(0, head) + a[0].slice(head).replace(/\d{3}/g, ',$&');
        return a.join('.');
    };
}

console.log((-123456789.0134).format());

Method 2 (Split to Array)

if (typeof Number.prototype.format === 'undefined') {
    Number.prototype.format = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        const a = this.toFixed(precision).split('.');

        a[0] = a[0]
            .split('').reverse().join('')
            .replace(/\d{3}(?=\d)/g, '$&,')
            .split('').reverse().join('');

        return a.join('.');
    };
}

Method 3 (Loop)

if (typeof Number.prototype.format === 'undefined') {
    Number.prototype.format = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('');
        a.push('.');

        var i = a.indexOf('.') - 3;
        while (i > 0 && a[i-1] !== '-') {
            a.splice(i, 0, ',');
            i -= 3;
        }

        a.pop();
        return a.join('');
    };
}

Usage Example

console.log('======== Demo ========')
console.log(
    (1234567).format(0),
    (1234.56).format(2),
    (-1234.56).format(0)
);
var n = 0;
for (var i=1; i<20; i++) {
    n = (n * 10) + (i % 10)/100;
    console.log(n.format(2), (-n).format(2));
}

Separator

If we want custom a thousands separator or decimal separator, use replace():

123456.78.format(2).replace(',', ' ').replace('.', ' ');

Test suite

function assertEqual(a, b) {
    if (a !== b) {
        throw a + ' !== ' + b;
    }
}

function test(format_function) {
    console.log(format_function);
    assertEqual('NaN', format_function.call(NaN, 0))
    assertEqual('Infinity', format_function.call(Infinity, 0))
    assertEqual('-Infinity', format_function.call(-Infinity, 0))

    assertEqual('0', format_function.call(0, 0))
    assertEqual('0.00', format_function.call(0, 2))
    assertEqual('1', format_function.call(1, 0))
    assertEqual('-1', format_function.call(-1, 0))

    // Decimal padding
    assertEqual('1.00', format_function.call(1, 2))
    assertEqual('-1.00', format_function.call(-1, 2))

    // Decimal rounding
    assertEqual('0.12', format_function.call(0.123456, 2))
    assertEqual('0.1235', format_function.call(0.123456, 4))
    assertEqual('-0.12', format_function.call(-0.123456, 2))
    assertEqual('-0.1235', format_function.call(-0.123456, 4))

    // Thousands separator
    assertEqual('1,234', format_function.call(1234.123456, 0))
    assertEqual('12,345', format_function.call(12345.123456, 0))
    assertEqual('123,456', format_function.call(123456.123456, 0))
    assertEqual('1,234,567', format_function.call(1234567.123456, 0))
    assertEqual('12,345,678', format_function.call(12345678.123456, 0))
    assertEqual('123,456,789', format_function.call(123456789.123456, 0))
    assertEqual('-1,234', format_function.call(-1234.123456, 0))
    assertEqual('-12,345', format_function.call(-12345.123456, 0))
    assertEqual('-123,456', format_function.call(-123456.123456, 0))
    assertEqual('-1,234,567', format_function.call(-1234567.123456, 0))
    assertEqual('-12,345,678', format_function.call(-12345678.123456, 0))
    assertEqual('-123,456,789', format_function.call(-123456789.123456, 0))

    // Thousands separator and decimal
    assertEqual('1,234.12', format_function.call(1234.123456, 2))
    assertEqual('12,345.12', format_function.call(12345.123456, 2))
    assertEqual('123,456.12', format_function.call(123456.123456, 2))
    assertEqual('1,234,567.12', format_function.call(1234567.123456, 2))
    assertEqual('12,345,678.12', format_function.call(12345678.123456, 2))
    assertEqual('123,456,789.12', format_function.call(123456789.123456, 2))
    assertEqual('-1,234.12', format_function.call(-1234.123456, 2))
    assertEqual('-12,345.12', format_function.call(-12345.123456, 2))
    assertEqual('-123,456.12', format_function.call(-123456.123456, 2))
    assertEqual('-1,234,567.12', format_function.call(-1234567.123456, 2))
    assertEqual('-12,345,678.12', format_function.call(-12345678.123456, 2))
    assertEqual('-123,456,789.12', format_function.call(-123456789.123456, 2))
}

console.log('======== Testing ========');
test(Number.prototype.format);
test(Number.prototype.format1);
test(Number.prototype.format2);
test(Number.prototype.format3);

Benchmark

function benchmark(f) {
    var start = new Date().getTime();
    f();
    return new Date().getTime() - start;
}

function benchmark_format(f) {
    console.log(f);
    time = benchmark(function () {
        for (var i = 0; i < 100000; i++) {
            f.call(123456789, 0);
            f.call(123456789, 2);
        }
    });
    console.log(time.format(0) + 'ms');
}

// If not using async, the browser will stop responding while running.
// This will create a new thread to benchmark
async = [];
function next() {
    setTimeout(function () {
        f = async.shift();
        f && f();
        next();
    }, 10);
}

console.log('======== Benchmark ========');
async.push(function () { benchmark_format(Number.prototype.format); });
next();
2 of 15
10

A simple option for proper comma placement by reversing the string first and basic regexp.

String.prototype.reverse = function() {
    return this.split('').reverse().join('');
};

Number.prototype.toCurrency = function( round_decimal /*boolean*/ ) {       
     // format decimal or round to nearest integer
     var n = this.toFixed( round_decimal ? 0 : 2 );

     // convert to a string, add commas every 3 digits from left to right 
     // by reversing string
     return (n + '').reverse().replace( /(\d{3})(?=\d)/g, '$1,' ).reverse();
};