/**
 * 千位数逗号格式化
 */
export const thousandFormat = (str, keep = 0) => {
    let res = str.toString()
    let reg = /^([0-9]+)(\.)([0-9]+)/g
    let decimal = ''
    // 判断是否有小数点
    if (reg.test(res) && keep > -1) {
        res = Number(str).toFixed(keep)
        decimal = keep === 0 ? '' : res.replace(reg, '$2$3')
        res = res.replace(reg, '$1')
    }

    reg = /^[0-9]+$/g
    // 判断是否为纯数字
    if (reg.test(res)) {
        const arr = res.split('')
        const cond = Math.ceil(arr.length / 3)

        if (cond > 1) {
            for (let i = 1; i < cond; i++) {
                arr[arr.length - 1 - i * 3] += ','
            }
        }

        res = ''
        arr.map((item) => (res += item))
        res += decimal
    } else {
        console.log('千位数逗号格式化，请传入数字')
    }

    return res
}
