网络编程 
首页 > 网络编程 > 浏览文章

js输出数据精确到小数点后n位代码

(编辑:jimmy 日期: 2025/7/6 浏览:3 次 )

编写两种方法,可以输出数据 num 精确到小数点后第 n 位,具体内容如下

1. 借助于 Math.pow(10,n);
2. 借助于 ..toFixed(n) (JS 1.5(IE5.5+,NS6+以上版本支持)。
测试 pi=3.14159265 的输出结果:
精确到小数点后 n 位, 借助于 Math.pow(10,n):
3.1
3.14
3.142
3.1416
精确到小数点后 n 位, 借助于 ..toFixed(n):
3.1
3.14
3.142
3.1416

<html>
<head>
  <title>四舍五入</title>
  <meta charset="utf-8">
</head>
<body>
<script>
function round_1(num,n){//返回数字 num, 精确到小数点后 n 位
  var number= Math.round(num*Math.pow(10,n));
  return number/Math.pow(10,n);
}
function round_2(num,n){//返回数字 num, 精确到小数点后 n 位
  return num.toFixed(n); //JS 1.5(IE5.5+,NS6+以上版本支持)
}
var pi= 3.14159265;
document.write("精确到小数点后 n 位, 借助于 Math.pow(10,n):<br>");
for (var i=1; i<5; i++)
document.write(round_1(pi,i) + "<br>"); 
document.write("精确到小数点后 n 位, 借助于 ..toFixed(n):<br>");
for (var i=1; i<5; i++)
document.write(round_2(pi,i) + "<br>");
</script> 
</body>
</html>

以上就是本文的全部内容,希望对大家学习javas程序设计有所帮助。

上一篇:JS实现n秒后自动跳转的两种方法
下一篇:学习Bootstrap滚动监听 附调用方法
一句话新闻
Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。