关于javascript:JavaScript-Math对象

9次阅读

共计 1541 个字符,预计需要花费 4 分钟才能阅读完成。

Math 对象

Math 对象用于执行数学工作。Math 对象并不像 Date 和 String 那样是对象的类,因而没有构造函数 Math()。

Math 对象属性

Math 对象办法

ceil()

ceil() 办法可对一个数进行向上取整。

语法

Math.ceil(x)

参数

1.x 必须。必须是一个数值。

TIPS
它返回的是大于或等于 x,并且与 x 最靠近的整数。

实例

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ceil()</title>
<script type="text/javascript">
    document.write(Math.ceil(3.3));
    document.write(Math.ceil(-0.1));
</script>
</head>
<body>
</body>
</html>

floor()

floor() 办法可对一个数进行向下取整。

语法

Math.floor(x)

参数

1.x 必须。任意数值或表达式。

TIPS
返回的是小于或等于 x,并且与 x 最靠近的整数。

实例

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>floor()</title>
<script type="text/javascript">
    document.write(Math.floor(3.3));
    document.write(Math.floor(-0.1));
</script>
</head>
<body>
</body>
</html>

round()

round() 办法可把一个数字四舍五入为最靠近的整数。

语法

Math.round(x)

参数

1.x 必须。必须是数字。

TIPS
1. 返回与 x 最靠近的整数。
2. 对于 0.5,该办法将进行上舍入。(5.5 将舍入为 6)
3. 如果 x 与两侧整数等同靠近,则后果靠近 +∞方向的数字值。(如 -5.5 将舍入为 -5; -5.52 将舍入为 -6)

实例

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>round()</title>
<script type="text/javascript">
    document.write(Math.round(3.3));
    document.write(Math.round(-0.1));
    document.write(Math.round(-9.9));
    document.write(Math.round(8.9));
</script>
</head>
<body>
</body>
</html>

random()

random() 办法可返回介于 0 ~ 1(大于或等于 0 但小于 1) 之间的一个随机数。

语法

Math.random();

TIPS
返回一个大于或等于 0 但小于 1 的符号为正的数字值。

实例

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Math </title>
<script type="text/javascript">
    document.write(Math.round((Math.random())*10)); // 生成一个不大于 10 的整数
</script>
</head>
<body>
</body>
</html>
正文完
 0