温馨提示×

温馨提示×

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

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

怎么在JavaScript中实现四舍五入精确到小数点

发布时间:2021-04-21 15:54:52 来源:亿速云 阅读:137 作者:Leah 栏目:编程语言

今天就跟大家聊聊有关怎么在JavaScript中实现四舍五入精确到小数点,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

Java的特点有哪些

Java的特点有哪些 1.Java语言作为静态面向对象编程语言的代表,实现了面向对象理论,允许程序员以优雅的思维方式进行复杂的编程。 2.Java具有简单性、面向对象、分布式、安全性、平台独立与可移植性、动态性等特点。 3.使用Java可以编写桌面应用程序、Web应用程序、分布式系统和嵌入式系统应用程序等。

第一种方法:

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位。

看完上述内容,你们对怎么在JavaScript中实现四舍五入精确到小数点有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

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

AI