You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中将数字转换为带K、M、B后缀的固定计数表示?

数字计数格式转换实现方案

你现有的格式化函数存在遗漏逻辑:当数值小于1000时没有定义返回规则,调用后会得到undefined,需要先补全这部分逻辑。

完善后的格式化函数

function formatter(cash) {
     if (cash >= 1000000000) {
        return (cash / 1000000000).toFixed(1).replace(/\.0$/, '') + 'B';
     }
     if (cash >= 1000000) {
        return (cash / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
     }
     if (cash >= 1000) {
        return (cash / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
     }
     // 新增小于1000的返回逻辑
     return cash;
}

函数调用方法

你只需要在所有需要展示格式化后数值的位置,把原始数值作为参数传入formatter()即可,函数会自动匹配阈值返回对应格式的结果。

基础调用示例

// 测试用例
console.log(formatter(800)) // 返回 800
console.log(formatter(1200)) // 返回 1.2K
console.log(formatter(2000)) // 返回 2K
console.log(formatter(4500000)) // 返回 4.5M
console.log(formatter(9000000000)) // 返回9B

页面渲染场景使用示例

如果你需要把格式化后的数值展示到页面上,把原来直接赋值原始数值的逻辑,替换为调用函数后再赋值即可,数值更新时重新调用一次就能自动刷新显示格式:

// 假设cash是你动态更新的数值变量
const cash = 12500;
// 原逻辑(直接显示原始数值)
// document.querySelector('.cash-display').innerText = cash;
// 修改后逻辑(显示格式化后数值)
document.querySelector('.cash-display').innerText = formatter(cash);

内容的提问来源于stack exchange,提问作者BlackcatGame77

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 06:24:02