如何使用JavaScript格式化数字?

如何使用JavaScript格式化数字?

问题描述:

我想使用JavaScript格式化数字。

I want to format numbers using JavaScript.

例如:

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


如果你想使用内置代码,您可以使用 toLocaleString( ) minimumFractionDigits ,尽管浏览器兼容 toLocaleString()上的扩展选项 受限

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'

如果您使用的是Node.js,则将需要 npm install intl 包。

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