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

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

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

``Math.round(value)``

``````<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

2.一个

3.一个

4.一个

5.安

``````<!-- 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``