数字字符串转换为带千分位逗号的格式

71 阅读1分钟

每周一题1-14

使用正则

核心就是正则表达式(/\B(?=(\d{3})+(?!\d))/g,',')

function solution(s) {
    // PLEASE DO NOT MODIFY THE FUNCTION SIGNATURE
    // write code here
    const numStr = parseFloat(s).toString();
    const [pre, nex] = numStr.split('.')
    const len = pre.length;
    let result = pre.replace(/\B(?=(\d{3})+(?!\d))/g,',')
    return nex ? result + '.' + nex : result;
}

function main() {
    console.log(solution("1294512.12412") === '1,294,512.12412');
    console.log(solution("0000123456789.99") === '123,456,789.99');
    console.log(solution("987654321") === '987,654,321');
}

main();

取余

核心就是一个循环,一个%3的判断条件

function solution(s) {
    // PLEASE DO NOT MODIFY THE FUNCTION SIGNATURE
    // write code here
    const numStr = parseFloat(s).toString();
    const [pre, nex] = numStr.split('.')
    const len = pre.length;
    let result = ''
    for (let i = len - 1; i >= 0; i--) {
        result = pre[i] + result
        if ((len - i) % 3 === 0 && i !== 0) {
            result = ',' + result
        }
    }
    return nex ? result + '.' + nex : result;
}

function main() {
    console.log(solution("1294512.12412") === '1,294,512.12412');
    console.log(solution("0000123456789.99") === '123,456,789.99');
    console.log(solution("987654321") === '987,654,321');
}

main();