zl程序教程

您现在的位置是:首页 >  后端

当前栏目

JS保留小数点(四舍五入、四舍六入)实现思路及实例

JS实例思路 实现 保留 小数点 四舍五入
2023-06-13 09:14:51 时间
复制代码代码如下:

<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<title>floatDecimal.html</title>
<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
<metahttp-equiv="description"content="thisismypage">
<metahttp-equiv="content-type"content="text/html;charset=gb2312">
<scripttype="text/javascript">
//保留两位小数
//功能:将浮点数四舍五入,取小数点后2位
functiontoDecimal(x){
varf=parseFloat(x);
if(isNaN(f)){
return;
}
f=Math.round(x*100)/100;
returnf;
}
//制保留2位小数,如:2,会在2后面补上00.即2.00
functiontoDecimal2(x){
varf=parseFloat(x);
if(isNaN(f)){
returnfalse;
}
varf=Math.round(x*100)/100;
vars=f.toString();
varrs=s.indexOf(".");
if(rs<0){
rs=s.length;
s+=".";
}
while(s.length<=rs+2){
s+="0";
}
returns;
}
functionfomatFloat(src,pos){
returnMath.round(src*Math.pow(10,pos))/Math.pow(10,pos);
}
//四舍五入
document.writeln("保留2位小数:"+toDecimal(3.14159267)+"<br/>");
document.writeln("强制保留2位小数:"+toDecimal2(3.14159267)+"<br/>");
document.writeln("保留2位小数:"+toDecimal(3.14559267)+"<br/>");
document.writeln("强制保留2位小数:"+toDecimal2(3.15159267)+"<br/>");
document.writeln("保留2位小数:"+fomatFloat(3.14559267,2)+"<br/>");
document.writeln("保留1位小数:"+fomatFloat(3.15159267,1)+"<br/>");
//五舍六入
document.writeln("保留2位小数:"+1000.003.toFixed(2)+"<br/>");
document.writeln("保留1位小数:"+1000.08.toFixed(1)+"<br/>");
document.writeln("保留1位小数:"+1000.04.toFixed(1)+"<br/>");
document.writeln("保留1位小数:"+1000.05.toFixed(1)+"<br/>");
//科学计数
document.writeln(3.1415.toExponential(2)+"<br/>");
document.writeln(3.1455.toExponential(2)+"<br/>");
document.writeln(3.1445.toExponential(2)+"<br/>");
document.writeln(3.1465.toExponential(2)+"<br/>");
document.writeln(3.1665.toExponential(1)+"<br/>");
//精确到n位,不含n位
document.writeln("精确到小数点第2位"+3.1415.toPrecision(2)+"<br/>");
document.writeln("精确到小数点第3位"+3.1465.toPrecision(3)+"<br/>");
document.writeln("精确到小数点第2位"+3.1415.toPrecision(2)+"<br/>");
document.writeln("精确到小数点第2位"+3.1455.toPrecision(2)+"<br/>");
document.writeln("精确到小数点第5位"+3.141592679287.toPrecision(5)+"<br/>");
</script>
</head>
<body>
ThisismyHTMLpage.<br>
</body>
</html>


javascript四舍五入保留两位小数

复制代码代码如下:


functioncount(){
  //alert("count");
  varsize=~~(document.getElementById("size").value);
  varvalue=0;
  for(vari=0;i<size;i++){
   varval=1*(document.getElementById("afterAdjScor"+i).value);
   if(null!=val){
    value=Math.round((1*(value+val))*100)/100;
   }
  }
  if(isNaN(value)){
   value="输入必须为数字类型";
  }
  document.getElementById("total").value=value;
 }

说明:~~XX:字符串转int
     1*XX:字符串转float
     Math.round((1*(value+val))*100)/100:四舍五入