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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章