How do I format numbers using JavaScript?

2019-01-01 13:22发布

I want to format numbers using JavaScript.

For example:

10     => 10.00
100    => 100.00
1000   => 1,000.00
10000  => 10,000.00
100000 => 100,000.00

标签: javascript
16条回答
骚的不知所云
2楼-- · 2019-01-01 13:56

If you're using jQuery, you could use the format or number format plugins.

查看更多
有味是清欢
3楼-- · 2019-01-01 13:57

If you want to use built-in code, you can use toLocaleString() with minimumFractionDigits, although browser compatibility for the extended options on toLocaleString() is limited.

var n = 100000;
var value = n.toLocaleString(
  undefined, // leave undefined to use the browser's locale,
             // or use a string like 'en-US' to override it.
  { minimumFractionDigits: 2 }
);
console.log(value);
// In en-US, logs '100,000.00'
// In de-DE, logs '100.000,00'
// In hi-IN, logs '1,00,000.00'

If you're using Node.js, you will need to npm install the intl package.

查看更多
高级女魔头
4楼-- · 2019-01-01 14:00

On browsers that support the ECMAScript® 2016 Internationalization API Specification (ECMA-402), you can use an Intl.NumberFormat instance:

var nf = Intl.NumberFormat();
var x = 42000000;
console.log(nf.format(x)); // 42,000,000 in many locales
                           // 42.000.000 in many other locales

if (typeof Intl === "undefined" || !Intl.NumberFormat) {
  console.log("This browser doesn't support Intl.NumberFormat");
} else {
  var nf = Intl.NumberFormat();
  var x = 42000000;
  console.log(nf.format(x)); // 42,000,000 in many locales
                             // 42.000.000 in many other locales
}

查看更多
看风景的人
5楼-- · 2019-01-01 14:00

This is an article about your problem. Adding a thousands-seperator is not built in to JavaScript, so you'll have to write your own function like this (example taken from the linked page):

function addSeperator(nStr){
  nStr += '';
  x = nStr.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;
}
查看更多
登录 后发表回答