js封装四舍五入精确到小数点的方法

2019-05-15  本文已影响0人  黑_童_话

最近一直在做关于数据处理以及显示这块的项目,在展示方面需要保持数据格式一致,比如都精确到小数点后2位,之前一直使用的是Math.round(num*100)/100,后来发现在整除的时候会出现浮点,反而让数据格式变的怪怪的,所以自己就封装了一个四舍五入的函数,并且自带0补位,保证数据结构一致,亲测有效,安利给你们哦!如果觉得好用,请记得点赞和分享,不胜感谢!

1.将下面的函数复制到你的代码中

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.使用方法

直接调用此函数:getRound(num,digits);//第一个参数为需要四舍五入的数字,第二个参数为精确到小数点几位,默认是2位

3.结果示例

上一篇 下一篇

猜你喜欢

热点阅读