JS分别取数值的整数部分和小数部分的几种方法
取数值整数部分
parseInt
parseInt(string, radix) string 为字符串,radix 为介于 2-36 之间的数。使用者告诉这个函数 string(比如 11)是 radix(比如 2)进制的,函数将默认返回 string 以十进制时显示的数。
Math.round()Math.ceil()和 Math.floor()方法进行取整
Math.round() 是四舍五入进行取整
Math.ceil() 是向上取整
Math.floor() 是向下取整
我们需要根据数值的正负值分别使用 Math.floor()和 Math.ceil()进行取整。正数使用 Math.floor()向下取整,负数使用 Math.ceil()向上取整。
使用 es6 中的 Math.trunc()方法进行取整
Math.trunc()是 es6 中新增的方法,方法会将数字的小数部分去掉,只保留整数部分。返回给定的数值的整数部分。
利用位操作符 | 进行取整
js
console.log(3.45 | 0) //3
console.log(-3.45 | 0) //-3