Skip to content

处理大数千分位 #91

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Twlig opened this issue Apr 2, 2022 · 0 comments
Open

处理大数千分位 #91

Twlig opened this issue Apr 2, 2022 · 0 comments

Comments

@Twlig
Copy link
Owner

Twlig commented Apr 2, 2022

处理大数千分位

  • 遍历
function formatNum(num) {
    var str = num + ''
    var len = str.length
    var n = len % 3
    var count = Math.floor(len/3) - (n == 0 ? 1 : 0)
    var newStr = ''
    for(let i = 0; i < count; i++) {
        newStr = ',' + str.slice(len - 3*(i+1), len - 3*i) + newStr
    }
    if(n == 0) {
        newStr =  str.slice(0,3) + newStr
    } else {
        newStr =  str.slice(0, n) + newStr
    }
    return newStr
}
  • 正则匹配
function formatNum(num) {
    var str = num + ''
    var result = str.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
    return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant