【问题标题】:How to format big numbers in JavaScript?如何在 JavaScript 中格式化大数字?
【发布时间】:2016-10-30 16:44:32
【问题描述】:

我有以下大数字:2.9364136545300044e+24 我注意将此值格式化为2,936,413.65

我该怎么做呢?有没有图书馆可以做到?

【问题讨论】:

  • 将数字转换为字符串,并从右边每三个字符添加一个逗号?
  • 是的。但我也需要注意较小的数字
  • 为什么我的建议不适用于较小的数字?

标签: javascript formatting currency biginteger


【解决方案1】:

您可以使用Intl.NumberFormat.prototype.formatString.prototype.slice()String.prototype.concat()

var number = 2.9364136545300044e+24;
var n = new Intl.NumberFormat().format(number);
var res = n.slice(0, 9).concat(".").concat(n.slice(10, 12));
console.log(res);

【讨论】:

  • 感谢您的回答。这个 API 有 polyfill 吗?
  • @Erik “polyfill”是什么意思?您正在使用哪种浏览器?
  • 我需要支持 IE9+ :(
  • 我发现 number.toLocaleString() 返回的结果与您的 new Intl.NumberFormat().format 相同)
  • @Erik 如果这是特定于语言环境的格式,我不会依赖它。不同的用户可能会得到不同的结果。
猜你喜欢
  • 1970-01-01
  • 2020-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-28
  • 2010-10-14
相关资源
最近更新 更多