js实现千分位保留两位小数

js实现千分位保留两位小数

啥话也不说直接上代码
代码:

function price(num){
    num = num + '';
    if (!num.includes('.')) {
        num += '.'
    }
    return num.replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
        return $1 + ',';
    }).replace(/\.$/,".00");
}

console.log(`原价++++++12232.1`,`千分位价格———————————————————${price('12232.1')}`)
console.log(`原价++++++12232`,`千分位价格———————————————————${price('12232')}`)
console.log(`原价++++++12232.13`,`千分位价格———————————————————${price('12232.13')}`)

结果:

原价++++++12232.1 千分位价格———————————————————12,232.1
原价++++++12232 千分位价格———————————————————12,232.00
原价++++++12232.13 千分位价格———————————————————12,232.13
发布了5 篇原创文章 · 获赞 3 · 访问量 2100

猜你喜欢

转载自blog.csdn.net/weixin_43719566/article/details/103614479