js中将金额格式化

将金额处理为以下格式:在这里插入图片描述
项目中很多地方都可能需要用到,所以可以将其封装为一个函数

<span class="momeyFont"></span>amountFun('1000','.momeyFont')
function amountFun(obj,ele){
    
    
//obj为传入的金额,且为字符串型,ele为需要金额格式化的元素
            var newStr = "";
            var count = 0;
            if(obj.indexOf(".")==-1){
    
    
                if(obj.charAt(0) == '0'){
    
     //不存在小数点时,判断第一位数字是否为0
                    obj = obj.substring(1);
                }
                for(var i=obj.length-1;i>=0;i--){
    
    
                    if(count % 3 == 0 && count != 0){
    
    
                        newStr = obj.charAt(i) + "," + newStr;
                    }
                    else{
    
    
                        newStr = obj.charAt(i) + newStr;
                    }
                    count++;
                }
                obj = newStr + ".00";
            }
            else{
    
    
                for(var i=obj.indexOf(".")-1;i>=0;i--){
    
    
                    if(count % 3 == 0 && count != 0){
    
    
                        newStr = obj.charAt(i) + "," + newStr;
                    }
                    else{
    
    
                        newStr = obj.charAt(i) + newStr;
                    }
                    count++;
                }

                obj = newStr + (obj + "00").substr((obj + "00").indexOf("."),3);
            }
            return $(ele).text(obj)
        }

Guess you like

Origin blog.csdn.net/Distance_123/article/details/115208232