如何在JavaScript中格式化大数字

How to format big numbers in JavaScript?

本文关键字:格式化 数字 JavaScript      更新时间:2023-09-26

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

我该怎么做呢?有没有库可以做呢?

您可以使用Intl.NumberFormat.prototype.format, String.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);

作为一个快速和简单的解决方案,您可以使用number.toLocaleString()

因为localString是基于浏览器定义的,不同的用户可能得到不同的结果。但是,您可以强制特定位置始终获得相同的格式。示例:toLocaleString('en-GB', { timeZone: 'UTC' })