JS中Math的常用方法:四舍五入round、向下取整floor、向上取整ceil、随机数random、绝对值abs、最小值min、最大值max、多次幂pow、平方根sqrt

 1 // 1.四舍五入
 2 Math.round(1.4); // 1
 3 Math.round(1.5); // 2
 4 
 5 // 2.向下取整(返回比参数小且最相邻的整数,注意:负小数易出错)
 6 Math.floor(1.234); //1
 7 Math.floor(-1.234); //-2
 8 
 9 // 3.向上取整(返回比参数大且最相邻的整数,注意:负小数易出错)
10 Math.ceil(1.234); //2
11 Math.ceil(-1.234); //-1
12 
13 // 4.返回0-1之间的随机数
14 Math.random();
15 
16 // 5.绝对值
17 Math.abs(1); // 1
18 Math.abs(-1); // 1
19 
20 // 6.返回两者中的较小值(ES3只有两个参数)
21 Math.min(1, 2, 3, 4); // 1
22 
23 // 7.返回两者中的较大值(ES3只有两个参数)
24 Math.max(1, 2, 3, 4); // 4
25 
26 // 8.返回多次幂。
27 Math.pow(2, 3); //8(2的3次方)
28 
29 // 9.返回平方根
30 Math.sqrt(9); //3

猜你喜欢

转载自www.cnblogs.com/joych3n/p/js-math.html
今日推荐