JavaScript Math.round()函数用法示例

2021年4月11日15:56:19 发表评论 671 次浏览

JavaScript中的Math.round()函数用于将作为参数传递的数字四舍五入到最接近的整数。

语法

Math.round(value)

参数:

要四舍五入到最接近的整数的数字。

返回值:

将作为参数传递的数字四舍五入到作为参数传递的函数后的结果。

下面是一些示例, 以说明Math.round()函数:

将数字四舍五入到最接近的整数:要将数字四舍五入到最接近的整数, 应按以下方式实现math.round()函数:

<script type = "text/javascript">
     var round =Math.round(5.8);
     document.write("Number after rounding : " + round); 
</script>

输出如下:

Number after rounding : 6

将负数四舍五入到最接近的整数

:Math.round()函数本身在作为参数传递给它时会舍入一个负数。要将负数四舍五入到最接近的整数, 应按以下方式实现Math.round()函数:

<script type = "text/javascript">
     var round =Math.round(-5.8);
     document.write("Number after rounding : " + round); 
</script>

输出如下:

Number after rounding : -6

Math.round()函数, 当参数的小数点为" .5"时

:下面的程序显示了参数十进制为" .5"时Math.round()函数的结果。

<script type = "text/javascript">
     var round =Math.round(-12.5);
     document.write("Number after rounding : " + round);
     var round =Math.round(12.51);
     document.write("Number after rounding : " + round); 
</script>

输出如下:

Number after rounding : -12
Number after rounding : 13

错误和异常

1. A

非数字字符串

作为参数传递的返回NaN

2.一个

大于1的整数数组

作为参数传递的返回NaN

3.一个

空变量

作为参数传递的返回NaN

4.一个

空字符串

作为参数传递的返回NaN

5.安

空数组

作为参数传递的返回NaN

以下示例说明了JavaScript中的Math.floor()函数:

<!-- NEGATIVE NUMBER EXAMPLE -->
<script type = "text/javascript">
     document.write(Math.round(-2)); 
     document.write(Math.round(-2.56));          
</script>

输出如下:

-2
-3
<!-- POSITIVE NUMBER EXAMPLE -->
<script type = "text/javascript">
     document.write(Math.round(2)); 
     document.write(Math.round(2.56));          
</script>

输出如下:

2
3
<!-- STRING EXAMPLE -->
<script type = "text/javascript">
     document.write(Math.floor("lsbin"));          
</script>

输出如下:

NaN
<!-- ADDITION INSIDE FUNCTION EXAMPLE -->
<script type = "text/javascript">
     document.write(Math.floor(7.2+9.3));           
</script>

输出如下:

17

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: