JavaScript Math对象

本文介绍了JavaScript Math对象的三个实用方法:ceil()向上取整、floor()向下取整和round()四舍五入。通过实例演示了如何在实际开发中使用这些数学运算工具。同时,还展示了Math.random()生成随机数的功能。
摘要由CSDN通过智能技术生成

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值