数值处理(取整、四舍五入、随机数等)
一. 保留数据
1.1 只保留整数部分
parseInt(1.23456) // 1
1.2 向下取整
Math.floor(1.23456) // 1
1.3 向上取整
Math.ceil(1.23456) // 2
1.4 四舍五入
Math.round(1.23456) // 1
Math.round(1.73456) // 2
1.5 取绝对值
Math.abs(-1) // 1
1.6 取两数中的较大值
Math.max(3,2) // 3
1.7 取两数中的较小值
Math.min(3,2) // 2
二. 随机数
2.1 随机数(0 - 1)
包含0,不包含1
Math.random();
2.2 随机整数
Math.random()
与Math.floor()
一起使用,返回随机整数
- 0 至 10 (包含0,不包含10)
Math.floor(Math.random() * 10)
- 1 至 10 (包含1、10)
Math.floor(Math.random() * 10) + 1
2.3 两个数之间的随机整数
- 包含 min ,不包含 max
function getRandomNum(min, max) { return Math.floor(Math.random() * (max - min) ) + min; } getRandomNum(1,2) //包含 1 ,不包含 2
- 包含 min 和 max
function getRandomNum(min, max) { return Math.floor(Math.random() * (max - min + 1) ) + min; } getRandomNum(1,2) //包含 1、2