如何格式化数字? [复制]

2024-04-29

我想使用 JavaScript 格式化数字。

例如:

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

如果你想使用内置代码,你可以使用toLocaleString() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString with minimumFractionDigits.

浏览器兼容性 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#Browser_compatibility对于扩展选项toLocaleString()我第一次写这个答案时受到限制,但目前的状态看起来不错。如果您使用的是 Node.js https://stackoverflow.com/a/23200062/241211,你需要npm install the intl https://www.npmjs.com/package/intl包裹。

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
  'de-CH',    // Switzerland
];
var n = 100000;
var opts = { minimumFractionDigits: 2 };
for (var i = 0; i < locales.length; i++) {
  console.log(locales[i], n.toLocaleString(locales[i], opts));
}

如果您来自与上述格式不同的文化,请edit https://stackoverflow.com/posts/30106316/edit这篇文章并添加您的区域设置代码。


1 Which you shouldn't.
2 Obviously do not use this for currency https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#using_options 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. Sometimes real e-commerce sites make this mistake.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何格式化数字? [复制] 的相关文章

随机推荐