千分位分隔符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const thousandth = (num = 123456789, fixed = 0) => {
    const strNum = num.toFixed(fixed)
    const [startStr, endStr] = strNum.split('.')
    let endIdx = startStr.length - 1
    let n = 0
    const res = []
    while(endIdx > -1){
        res.unshift(startStr[endIdx])
        n++
        if(n % 3 === 0 && endIdx !== 0){
            res.unshift(',')
        }
        endIdx--
    }
    return endStr ? `${res.join('')}.${endStr}` : res.join('')
}

  从后往前 三位一切

1
2
3
4
5
6
7
8
9
10
11
12
13
const thousandth = (num = 123456789, fixed = 2) => {
    if (typeof num !== 'number') return new Error('请传入数字')
    const [startStr, endStr] = num.toFixed(fixed).split('.')
    const res = []
    for (let i = startStr.length; i > -1; i -= 3) {
        if (i > 3) {
            res.unshift(',', ...startStr.slice(i - 3, i))
        } else {
            res.unshift(...startStr.slice(0, i))
        }
    }
    return endStr ? `${res.join('')}.${endStr}` : res.join('')
}

  

posted @   671_MrSix  阅读(178)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示