How to format numbers? [duplicate]

Solution 1:

If you want to use built-in code, you can use toLocaleString() with minimumFractionDigits.

Browser compatibility for the extended options on toLocaleString() was limited when I first wrote this answer, but the current status looks good. If you're using Node.js, you will need to npm install the intl package.

var value = (100000).toLocaleString(
  undefined, // leave undefined to use the visitor's browser 
             // locale or a string like 'en-US' to override it.
  { minimumFractionDigits: 2 }
);
console.log(value);

Number formatting varies between cultures. Unless you're doing string comparison on the output,1 the polite thing to do is pick undefined and let the visitor's browser use the formatting they're most familiar with.2

// Demonstrate selected international locales
var locales = [
  undefined,  // Your own browser
  'en-US',    // United States
  'de-DE',    // Germany
  'ru-RU',    // Russia
  'hi-IN',    // India
];
var n = 100000;
var opts = { minimumFractionDigits: 2 };
for (var i = 0; i < locales.length; i++) {
  console.log(locales[i], n.toLocaleString(locales[i], opts));
}

If you are from a culture with a different format from those above, please edit this post and add your locale code.


1 Which you shouldn't.
2 Obviously do not do this for currency with something like {style: 'currency', currency: 'JPY'} unless you have converted to the local exchange rate. You don't want your website to tell people the price is ¥300 when it's really $300. I have seen real e-commerce sites make this mistake.

Solution 2:

Short solution:

var n = 1234567890;
String(n).replace(/(.)(?=(\d{3})+$)/g,'$1,')
// "1,234,567,890"

Solution 3:

Use

num = num.toFixed(2);

Where 2 is the number of decimal places

Edit:

Here's the function to format number as you want

function formatNumber(number)
{
    number = number.toFixed(2) + '';
    x = number.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

Sorce: www.mredkj.com