其他分享
首页 > 其他分享> > 数字千分位增加标点

数字千分位增加标点

作者:互联网

参考:https://www.jianshu.com/p/928c68f92c0c


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        let num = 1234567;
        let arr = num.toString().split('').reverse()
        console.log(arr, '==arr')
        let num1 = 8 - arr.length
        if (num1) {
            for (let i = 0; i < num1; i++) {
                arr.push('0')
            }
        }

        let arrtotal = []
        for (let j = 0; j < arr.length; j++) {
            if (j % 3 == 0 && j != 0) {
                arrtotal.push(',')
            }
            arrtotal.push(arr[j])

        }
        console.log(arrtotal.reverse().join(''))
    </script>

    <script>
        function numFormat(num) {
            num = num.toString().split(".");  // 分隔小数点
            var arr = num[0].split("").reverse();  // 转换成字符数组并且倒序排列
            var res = [];
            for (var i = 0, len = arr.length; i < len; i++) {
                if (i % 3 === 0 && i !== 0) {
                    res.push(",");   // 添加分隔符
                }
                res.push(arr[i]);
            }
            res.reverse(); // 再次倒序成为正确的顺序
            if (num[1]) {  // 如果有小数的话添加小数部分
                res = res.join("").concat("." + num[1]);
            } else {
                res = res.join("");
            }
            return res;
        }

        var a = 1234567894532;
        var b = 673439.4542;
        console.log(numFormat(a)); // "1,234,567,894,532"
        console.log(numFormat(b)); // "673,439.4542"
    </script>
    <script>
        // 2.方法二
        // 使用JS自带的函数 toLocaleString
        var a = 1234567894532;
        var b = 673439.4542;

        console.log(a.toLocaleString());  // "1,234,567,894,532"
        console.log(b.toLocaleString());  // "673,439.454"  (小数部分四舍五入了)
    </script>

    <script>
        function numFormat(num) {
            var res = num.toString().replace(/\d+/, function (n) { // 先提取整数部分
                return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
                    return $1 + ",";
                });
            })
            return res;
        }

        var a = 1234567894532;
        var b = 673439.4542;
        console.log(numFormat(a)); // "1,234,567,894,532"
        console.log(numFormat(b)); // "673,439.4542"

    </script>
</body>

</html>

标签:arr,console,数字,res,千分,标点,num,var,log
来源: https://blog.csdn.net/qq_42374676/article/details/120654438