JavaScript Math对象方法 | 您所在的位置:网站首页 › javascriptmath对象 › JavaScript Math对象方法 |
round() 方法可把一个数字四舍五入为最接近的整数。 语法: Math.round(x)注意: 1. 返回与 x 最接近的整数。 2. 对于 0.5,该方法将进行上舍入。(5.5 将舍入为 6) 3. 如果 x 与两侧整数同等接近,则结果接近 +∞方向的数字值 。(如 -5.5 将舍入为 -5; -5.52 将舍入为 -6),如下图: 把不同的数舍入为最接近的整数,代码如下: document.write(Math.round(1.6)+ ""); document.write(Math.round(2.5)+ ""); document.write(Math.round(0.49)+ ""); document.write(Math.round(-6.4)+ ""); document.write(Math.round(-6.6));
运行结果: 2 3 0 -6 -7 随机数 random() random() 方法可返回介于 0 ~ 1(大于或等于 0 但小于 1 )之间的一个随机数。语法: Math.random();注意:返回一个大于或等于 0 但小于 1 的符号为正的数字值。 我们取得介于 0 到 1 之间的一个随机数,代码如下: document.write(Math.random());运行结果: 0.190305486195328 注意:因为是随机数,所以每次运行结果不一样,但是0 ~ 1的数值。获得0 ~ 10之间的随机数,代码如下: document.write((Math.random())*10);运行结果: 8.72153625893887
|
CopyRight 2018-2019 实验室设备网 版权所有 |