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

2026-01-22 0 27,815

js四舍五入精确到小数点.png

第一种方法:

Math.round(num*100)/100

第二种方法:
1.复制下面内容放进代码
function getRound(num,digits=2) {
let temp=num;
num=Math.round(num*(Math.pow(10,(digits+1))))/(Math.pow(10,(digits+1)));
let tm 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
}
}pStr=String(num);
let tmpArr=tmpStr.split(".");
if(tmpArr.length==1){
if(digits==0){
return num
}else {
let str='';
for(let i=0;i
str+='0';
}
return num+'.'+str;
}
}else if(tmpArr.length==2){
if(digits==0){
return Math.round(temp)
}else {
let tmp=String(tmpArr[1]);
if(tmp.length>digits){
tmp=tmp.slice(0,digits+1);
if(tmp>digits){
tmp=Number(tmp)/10;
}
tmp=parseInt(tmp);
}
let str=String(tmp);
if(str.length
for(let i=str.length;i
str+='0';
}
}
tmp=tmpArr[0]+'.'+str;
return tmp;
}
}
}
2.直接调用此函数:
getRound(num,digits);//第一个参数为需要四舍五入的数字

第二个参数为精确到小数点几位,默认是2位。

推荐操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 web开发 js四舍五入精确到小数点的方法 https://www.zhiup.top/10223.html

相关