欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaScript中用于四舍五入的Math.round()方法讲解

程序员文章站 2023-11-27 21:27:28
 此方法返回一个数四舍五入为最接近的整数的值。 语法 math.round( x ) ; 下面是参数的详细信息:  ...

 此方法返回一个数四舍五入为最接近的整数的值。
语法

math.round( x ) ;

下面是参数的详细信息:

  •     x: 一个数字

返回值:

  • 返回数字四舍五入为最接近的整数的值。

例子:

<html>
<head>
<title>javascript math round() method</title>
</head>
<body>
<script type="text/javascript">

var value = math.round( 0.5 );
document.write("first test value : " + value ); 
 
var value = math.round( 20.7 );
document.write("<br />second test value : " + value ); 

var value = math.round( 20.3 );
document.write("<br />third test value : " + value ); 

var value = math.round( -20.3 );
document.write("<br />fourth test value : " + value ); 
</script>
</body>
</html>

这将产生以下结果:

first test value : 1
second test value : 21
third test value : 20
fourth test value : -20