方法1:使用 parseInt()
parseInt() 函数可解析一个字符串,并返回一个整数。
当参数 radix 的值为 0,或没有设置该参数时,parseInt() 会根据 string 来判断数字的基数。
当忽略参数 radix , JavaScript 默认数字的基数如下:
-
如果 string 以 "0x" 开头,parseInt() 会把 string 的其余部分解析为十六进制的整数。
-
如果 string 以 0 开头,那么 ECMAScript v3 允许 parseInt() 的一个实现把其后的字符解析为八进制或十六进制的数字。
-
如果 string 以 1 ~ 9 的数字开头,parseInt() 将把它解析为十进制的整数。
示例:使用 parseInt() 来解析不同的字符串
parseInt("10");
parseInt("10.33");
parseInt("11 22 33");
parseInt("60");
parseInt("40 year");
parseInt("he was 40");
parseInt("10",10);
parseInt("010");
parseInt("10",8);
parseInt("ox10");
parseInt("10",16);
输出 alert(parseInt(var))
10
10
11
60
40
NaN
10
10
8
16
16
方法2:两次取反
var decimal=4;
var integer = ~~decimal; // 4 = ~~4.123
console.log(integer); 4
方法3:Math.floor()向下取整
Math.floor():返回小于参数值的最大整数。
console.log(Math.floor(2.5)); //2
console.log(Math.floor(-2.5)); //-3
方法4:Math.ceil()向上取整
Math.ceil():返回大于参数值的最小整数。
console.log(Math.ceil(2.5)); //3
console.log(Math.ceil(-2.5)); //-2
方法5:Math.round()四舍五入
Math.round():四舍五入。
console.log(Math.round(2.5)); //3
console.log(Math.round(-2.5)); //-2
console.log(Math.round(-2.6)); //-3