javascript将浮点数转换成整数

Summary

临时我就想到3个方法而已。假设读者想到其它好用方法,也能够交流一下

  1. parseInt
  2. 位运算符
  3. 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)//22

2. 转换规则:
  • (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. 实例
 console.log(0 | "123.45")//123

    console.log(0 | 123.45)//123

    console.log(0 ^ 123.45)//123

    console.log(~~123.45)//123


2. 原理:javascript没有整数的概念。全部的数值型都是双精度浮点数。在用位运算符时,它会先把操作数转变成整数。方便操作。

而0与其它值异或或者按位或都不会改变操作值的

三、Math.floor与Math.ceil
1. 实例
   console.log(Math.floor(2.3)//2
    console.log(Math.floor(-2.3)//-3
    console.log(Math.ceil(2.3)//3
    console.log(Math.ceil(-2.3)//-2

2. 两者不足:Math.floor得到的是数字的最小整数;而Math.ceil得到的是最大整数。所以导致本来-2.3我们取整的话我们要得到的是-2。可是用Math.floor得到的是-3。而2.3用Math.ceil得到的是3。可是我们要的是2即可了。
3. 解决:
//自行定义一个函数
function getInt(val){

   return val>0 ? Math.floor(val):Math.ceil(val);

}


Reference

What is the best method to convert floating point to an integer in JavaScript
parseInt MDN
Why doesn't an octal literal as a string cast to a number?

猜你喜欢

转载自www.cnblogs.com/xfgnongmin/p/10767549.html