1、写在前面,最最常用几个方法:
绝对值:Math.abs(x)
最大值:Math.max([x[, y[, …]]])
最小值:Math.min([x[, y[, …]]])
随机值:Math.random()
向上取整:Math.ceil(x)
向下取整:Math.floor(x)
四舍五入:Math.round(x)
2、 常用方法
一、Math.floor(向下取整)
作用:返回小于等于参数的最大整数。
eg:
Math.floor(5.65) //返回5
Math.floor(2.4) //返回2
Math.floor(1.5) //返回2
Math.floor(-1.5) //返回-2
Math.floor(-5.8) //返回-6
二、Math.ceil(向上取整)
作用:返回大于等于参数的最小整数
eg:
Math.ceil(5.65) //返回6
Math.ceil(2.4) //返回3
Math.ceil(1.5) //返回2
Math.ceil(-1.5) //返回-1
Math.ceil(-5.8) //返回-5
三、Math.round(四舍五入)
作用:四舍五入,返回参数+0.5后,向下取整。(简单来说就是不管正负数,统一加上0.5,再向下取数。向下的意思是往小的方向取,如Math.round(-8.6)先-8.6+0.5=-8.1,再向下取整得到-9)
eg:
Math.round(5.65) //返回6
Math.round(2.4) //返回2
Math.round(1.5) //返回2
Math.round(-1.5) //返回-1
Math.round(-5.8) //返回-6
四、parseInt(简单理解为直接舍去小数部分取整)
作用:解析一个字符串,并返回一个整数,这里可以简单理解成返回舍去参数的小数部分后的整数。
eg:
parseInt(5.65) //返回5
parseInt(2.4) //返回2
parseInt(1.5) //返回1
parseInt(-1.5) //返回-1
parseInt(-5.8) //返回-5