如何使用JavaScript实现大数字缩写(如将1.000.000转为1M)?
JavaScript 实现长数字缩写的可行方案
核心实现逻辑基于千进制量级匹配,对应标准的数字缩写后缀,可兼顾展示精度与可读性,完全满足长数字缩写的展示需求。
核心实现规则
- 阈值按千进制分层,对应固定缩写后缀:10³ 对应
k、10⁶ 对应M、10⁹ 对应B、10¹² 对应T - 数值小于1000时直接展示原整数,不附加缩写单位
- 超过层级阈值的数值做等比缩放,可自定义保留小数位数,自动剔除末尾无意义的0值
可直接复用的自定义实现代码
function formatCompactNumber(num, decimalPlaces = 1) { // 边界值处理 if (isNaN(Number(num))) return '0' if (Number(num) === 0) return '0' const absoluteNum = Math.abs(Number(num)) // 量级与后缀映射表 const levelList = [ { threshold: 1e12, suffix: 'T' }, { threshold: 1e9, suffix: 'B' }, { threshold: 1e6, suffix: 'M' }, { threshold: 1e3, suffix: 'k' } ] for (const level of levelList) { if (absoluteNum >= level.threshold) { // 缩放计算并控制精度 let scaledVal = Number(num) / level.threshold scaledVal = scaledVal.toFixed(decimalPlaces) // 清除末尾无意义的0 scaledVal = scaledVal.replace(/\.0+$|(\.\d*?)0+$/, '$1') return `${scaledVal}${level.suffix}` } } // 小于1000的数值直接返回 return String(num) }
常见调用效果
- 执行
formatCompactNumber(1000)返回1k - 执行
formatCompactNumber(10000)返回10k - 执行
formatCompactNumber(1000000)返回1M - 执行
formatCompactNumber(1256000, 2)返回1.26M - 执行
formatCompactNumber(999)返回999
原生API简化方案
如果运行环境支持ES2020(主流现代浏览器、Node.js 13+均已兼容),无需手写映射逻辑,可直接使用内置Intl.NumberFormat实现缩写效果:
// 配置为英文语言环境时,输出效果和示例需求完全匹配 const compactNumFormatter = new Intl.NumberFormat('en', { notation: 'compact', compactDisplay: 'short' }) // 调用示例 compactNumFormatter.format(1234567) // 输出 "1.2M" compactNumFormatter.format(10000) // 输出 "10k" compactNumFormatter.format(1000) // 输出 "1k"
注意:原生方案支持自定义语言环境的缩写规则,会自动适配不同地区的展示习惯,无需额外维护映射关系,性能优于自定义实现方案。
内容的提问来源于stack exchange,提问作者heagan
相关产品推荐
相关产品推荐

