javascript - 取大数字(例如1900234)并在每三位数字后加逗号的最快方法是什么?
问题描述
我正在做一个实习项目,虽然它不关注绩效,但我希望尽可能快(和精益)。到目前为止,我有一个工作版本(有一个错误)和一个上述功能的概念:
V1(BUG:无法处理带点和逗号的数字。)
function addCommas(nStr) {
if (isNaN(nStr)) {
throw new Error(`${nStr} is NaN`);
}
// Alternative: isNaN(nStr) ? throw new Error(`${nStr} is NaN`) : nStr += ``;
nStr += ``;
// If the input is of the form 'xxxx.yyy', split it into x1 = 'xxxx'
// and x2 = '.yyy'.
let x = nStr.split(`.`);
let x1 = x[0];
let x2 = x.length > 1 ? `.` + x[1] : ``;
let rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
// x1 takes the form 'x,xxx' - no matter how long the number,
// this is where the commas are added after every three digits.
x1 = x1.replace(rgx, `$1` + `,` + `$2`);
}
return x1 + x2;
}
V2 概念(看起来较慢但没有已知错误)
function addCommas(nStr) {
if (isNaN(nStr)) {
throw new Error(`${nStr} is NaN`);
}
nStr += ``;
// Remove any potential dots and commas.
nStr = nStr.replace(`.`, ``);
nStr = nStr.replace(`,`, ``);
// Split the number into an array of digits using String.prototype.split().
// Iterate digits. After every three, add a comma.
// Transform back into a string.
return nStr;
}
解决方案
查看函数 toLocaleString:
const b = 5120312039;
console.log(b.toLocaleString()); //"5,120,312,039"
推荐阅读
- c# - 我想打印频率最高的数字
- python - 将 Docker 运行转换为 Kubernetes 的问题
- python - 不同窗口大小的熊猫分组滚动平均值 - 不同时期的移动平均值
- identityserver4 - 如何找出在 IdentityServer 中使用最佳流程?
- c# - Blazor 中的缓存标识帮助程序
- laravel - dynamodb 查询我试图使用 laravel 从 dynamodb 获取一些数据
- sql - 光标替换
- python - 虚拟环境使用 pip 版本 9 创建, pip --version 显示版本 20
- enterprise-architect - 有没有办法在 Sparx Enterprise Architect 中列出包的元素?
- swift - 加快 CI 上的 fastlane