JavaScript 数学函数 数字取整和四舍五入等数字方法
- 取整,只保留整数(舍弃小数) parseInt(5.4625) // 5
- 向上取整,有小数,整数就+1 Math.ceil(5.1234) // 6
- 向下取整,(<=该数值的最大整数)和parseInt() 一样 Math.floor(5.642) // 5
- 四舍五入:
Math.round(5.1234); // 5
Math.round(5.6789); // 6 - 绝对值 Math.abs(-1); // 1
- 返回两者中的较大值 Math.max(3,6); // 6
- 返回两者中的较小值 Math.min(3,6); // 3
- 随机数(0-1) Math.random();
关于parseInt和Math.floor:
他们都是只保留整数部分,但是在转换时可能出现不一样的情况:
当有16为小数的时候,且最后一位小数位5时,去的值取数值的最大值。
Math.floor(5.999999999999995); // 5
当有16为小数的时候,且最后一位小数位6时,去的值取数值的最大值+1。
Math.floor(5.999999999999996); // 6