最近一直在做關(guān)于數(shù)據(jù)處理以及顯示這塊的項目,在展示方面需要保持數(shù)據(jù)格式一致,比如都精確到小數(shù)點后2位,之前一直使用的是Math.round(num*100)/100,后來發(fā)現(xiàn)在整除的時候會出現(xiàn)浮點,反而讓數(shù)據(jù)格式變的怪怪的,所以自己就封裝了一個四舍五入的函數(shù),并且自帶0補位,保證數(shù)據(jù)結(jié)構(gòu)一致,親測有效,安利給你們哦!如果覺得好用,請記得點贊和分享,不勝感謝!
1.將下面的函數(shù)復制到你的代碼中
function getRound(num,digits=2) {
num=Math.round(num*(Math.pow(10,(digits))));
num=num/(Math.pow(10,digits));
let tempstr=String(num);
let temp=tempstr.indexOf(".");
if(digits==0){
return parseInt(tempstr);
}else {
if(temp>=0){
tempstr.slice(temp,temp+digits);
for(let i=temp+1;i
if(tempstr.charAt(i)==undefined||tempstr.charAt(i)==null||tempstr.charAt(i)==""){
tempstr+='0'
? ? ? ? ? ? ? ? }
}
}else{
tempstr+='.';
for(let i=0;i
tempstr+='0';
}
}
return tempstr
? ? }
}
2.使用方法
直接調(diào)用此函數(shù):getRound(num,digits);//第一個參數(shù)為需要四舍五入的數(shù)字,第二個參數(shù)為精確到小數(shù)點幾位,默認是2位
3.結(jié)果示例





