如何设置数字格式?

2022-08-30 02:24:11

我想使用JavaScript格式化数字。

例如:

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

答案 1

如果要使用内置代码,可以将 toLocaleString() 与 .minimumFractionDigits

当我第一次写这个答案时,扩展选项的浏览器兼容性受到限制,但当前状态看起来不错。如果您使用的是 Node.js,则需要使用 intl 包。toLocaleString()npm install

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);

数字格式因区域性而异。除非您对输出进行字符串比较,否则礼貌的做法是选择并让访问者的浏览器使用他们最熟悉的格式。阿拉伯数字undefined

// 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));
}

如果您来自与上述文化格式不同的文化,请编辑此帖子并添加您的区域设置代码。


1 你不应该这样做。
2 显然,除非您已转换为当地汇率,否则不要将其用于{style:'currency',currency:'JPY'}之类的货币。你不希望你的网站告诉人们价格是300日元,而实际上它是300美元。有时,真正的电子商务网站会犯这个错误。


答案 2

简短的解决方案:

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