JavaScript中Math.round()与Math.pow()实现四舍五入详解
作者:小括号时间:2026-10-27 20:31:57浏览:383
本文介绍JavaScript中Math.round()和Math.pow()函数的基本用法,并通过ForDight和cheng两个自定义函数演示如何实现指定小数位数的四舍五入。包含完整HTML示例代码及按钮交互测试方法,适用于前端开发中的数值格式化需求。
JavaScript Math.round与Math.pow基础用法
代码示例如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>JavaScript四舍五入(Math.round()与Math.pow())</title>
<script type="text/javascript">
//Math.round(x);返回数字最接近的整数,即对小数部分进行四舍五入取整
function f(){
alert(Math.round(123.567));
alert(Math.round(123.456));
}
//Math.pow(x,y);返回底数x的y次幂
//等同于计算x的y次幂的数值表达式
//若pow参数过大导致浮点溢出,则返回Infinity
function f1(){
alert(Math.pow(2,10));//2的10次方等于1024
alert(Math.pow(1024,0.1));//1024的0.1次方等于2
alert(Math.pow(99,9999));//溢出则返回Infinity
}
实现指定小数位数的四舍五入方法/*JavaScript设置要保留的小数位数,并进行四舍五入。
*ForDight(Dight,How):数值格式化函数,其中Dight为待格式化的数字,How为要保留的小数位数。
*该方法原理是先乘以10的How次幂,舍去小数部分后再除以10的How次幂。
*/
function ForDight(Dight,How){
Dight = Math.round(Dight*Math.pow(10,How))/Math.pow(10,How);
return Dight;
}
function f2(){
alert(ForDight(12345.67890,3));//保留三位小数
alert(ForDight(123.99999,4));//保留四位小数
}
//另一种四舍五入方法,原理相同。
//参数num为待转换数据,n为要保留的位数
//调用示例:cheng(123.456,2);//保留两位小数
function cheng(num,n){
var dd=1;
var tempnum;
for(i=0;i<n;i++){
dd*=10;
}
tempnum = num*dd;
tempnum = Math.round(tempnum);
alert(tempnum/dd);
}
</script>
</head>
<body>
<input type="button" value="round" onclick="f();" />
<input type="button" value="pow" onclick="f1();" />
<input type="button" value="设置要保留的小数位数,四舍五入" onclick="f2();" />
<input type="button" value="cheng" onclick="cheng(123.456,2);" />
</body>
</html>作者最新文章
JS语法错误会阻止加载吗?区分SyntaxError与资源加载失败
2026-11-05 16:08:46
JavaScript常见SyntaxError语法错误排查与修复方法
2026-11-05 13:58:44
JS中slice、substring和substr截取字符串的区别
2026-11-05 13:43:47
JS 转 TS 手动迁移最佳实践:从配置 tsconfig 到消除 any 类型
2026-11-05 11:53:32
为什么JS数组push后得到的是数字而不是数组?
2026-11-05 09:59:18
