javascript将浮点数转换成整数的三个方法
浮点数转换成整数方法有很多,本例为大家介绍常用的三个方法,如果读者想到其他好用方法,也可以交流一下
Summary
暂时我就想到3个方法而已。如果读者想到其他好用方法,也可以交流一下
parseInt 位运算符 Math.floor Math.ceil
Description
一、parseInt
1. 实例
1 parseInt("13nash");//13 2 parseInt("")// NaN 3 parseInt("0xA") //10(十六进制) 4 parseInt(" 13")//13 5 parseInt("070")//ES3为56(八进制) ES5为70 6 parseInt(070)//ES3和ES5都为56 7 parseInt(22.5)//222. 转换规则:
(1). 根据实例(1)得出parseInt会解析一直到非数字时停止 (2). 根据实例(2)得出parseInt解析空字符串时为NaN,而不是0 (3). 根据实例(3)得出parseInt可以将16进制数转换成10进制 (4). 根据实例(4)得出parseInt忽略字符串的空格
3. 缺点:
(1). 根据实例(5)我们可以知道parseInt在转换八进制数组时是不兼容的。ES3会把070看成八进制数值,但是ES5会将070看成十进制。 (2). 根据实例(6)(7)我们可以知道parseInt在执行的时候会先把参数转变成字符串后再执行变成整数
4. 解释:为什么(5)(6)执行都是执行将070转换成整数,但是结果不一样呢?这个也是解决怎么得到缺点中的第二点。
因为在看官方文档中我看到了If string is not a string, then it is converted to one。这段话。就是说参数如果不是字符串的话,它会先将它转换成字符串再转换成整数。比如实例(6)中parseInt(070),其实是先将070转换成字符串,你可以试下070+""或者String(070)都可以知道070会被转换成"56",因为070是一个八进制。然后就变成了parseInt("56"),最后得出来的整数就是56了。不管你在ES3或者ES5都是为56
二、位操作符
1. 实例
1 console.log(0 | "123.45")//123 2 console.log(0 | 123.45)//123 3 console.log(0 ^ 123.45)//123 4 console.log(~~123.45)//123三、Math.floor与Math.ceil
1. 实例
1 console.log(Math.floor(2.3)//2 2 console.log(Math.floor(-2.3)//-3 3 console.log(Math.ceil(2.3)//3 4 console.log(Math.ceil(-2.3)//-23. 解决:
//自行定义一个函数 function getInt(val){ return val>0 ? Math.floor(val):Math.ceil(val); }

浙公网安备 33010602011771号