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

发布时间:2021-03-04 12:31:44 作者:小新
来源:亿速云 阅读:484

小编给大家分享一下js四舍五入精确到小数点的方法有哪些,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

第一种方法:

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<digits+temp+1;i++){ <="" div="">
if(tempstr.charAt(i)==undefined||tempstr.charAt(i)==null||tempstr.charAt(i)==""){
tempstr+='0'
}
}
}else{
tempstr+='.';
for(let i=0;i<digits;i++){ <="" div="">
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<digits;i++){ <="" div="">
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<digits){ <="" div="">
for(let i=str.length;i<digits;i++){ <="" div="">
str+='0';
}
}
tmp=tmpArr[0]+'.'+str;
return tmp;
}
}
}

2.直接调用此函数:

getRound(num,digits);//第一个参数为需要四舍五入的数字

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

以上是“js四舍五入精确到小数点的方法有哪些”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. PHP小数点后保留位数并四舍五入
  2. Js BigDecimal实现精确加减乘除运算的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js

上一篇:python中怎样实现字符与ascll码相互转换

下一篇:java中回收弱引用的方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》