JS 浮点数转整数的方法

1.  parseInt

概念:以第二个参数为基数来解析第一个参数字符串,通常用来做十进制的取整(省略小数)如:parseInt(2.7) //结果为2

特点:接收两个参数parseInt(string,radix)

['1','2','3'].map(parseInt)结果

result:[1, NaN, NaN]

['1','2','3'].map(parseInt) 就是将字符串1,2,3作为元素;0,1,2作为下标分别调用 parseInt 函数。即分别求出 parseInt('1',0), parseInt('2',1), parseInt('3',2)的结果

2.位运算

1 console.log("123.45"| 0)//123

2 console.log(123.45 | 0)//123

3 console.log(123.45 ^ 0)//123

4 console.log(~~123.45)//123

浮点数是不支持位运算的,所以会先把1.1转成整数1再进行位运算,就好像是对浮点数向下求整。所以1|0的结果就是1

删除最后一个数字

按位或运算符还可以用于从整数的末尾删除任意数量的数字。这意味着我们不需要使用这样的代码来在类型之间进行转换。

  1. let str = "1553";

  2. Number(str.substring(0, str.length - 1));

相反,按位或运算符可以这样写:

  1. console.log(1553 / 10 | 0) // Result: 155

  2. console.log(1553 / 100 | 0) // Result: 15

  3. console.log(1553 / 1000 | 0) // Result: 1

3. Math

  • Math.round:四舍五入;Math.round(3.6) == 4
  • Math.ceil:向上取整;Math.ceil(3.4) == 4
  • Math.floor:向下取整;Math.floor(3.6) == 3
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章