JS將小數轉為整數的方法:1、使用“parseInt(小數值)”語句;2、使用“~~小數值”語句;3、使用“Math.floor(小數值)”語句;4、使用“Math.ceil(小數值)”語句;5、使用“Math.round(小數值)”語句。
本教程操作環境:windows7系統、javascript1.8.5版、Dell G3電腦。
方法1:使用 parseInt()
parseInt() 函數可解析一個字符串,并返回一個整數。
當參數 radix 的值為 0,或沒有設置該參數時,parseInt() 會根據 string 來判斷數字的基數。
當忽略參數 radix , JavaScript 默認數字的基數如下:
-
如果 string 以 "0x" 開頭,parseInt() 會把 string 的其余部分解析為十六進制的整數。
-
如果 string 以 0 開頭,那么 ECMAScript v3 允許 parseInt() 的一個實現把其后的字符解析為八進制或十六進制的數字。
-
如果 string 以 1 ~ 9 的數字開頭,parseInt() 將把它解析為十進制的整數。
示例:使用 parseInt() 來解析不同的字符串
document.write(parseInt("10") + "<br>"); document.write(parseInt("10.33") + "<br>"); document.write(parseInt("34 45 66") + "<br>"); document.write(parseInt(" 60 ") + "<br>"); document.write(parseInt("40 years") + "<br>"); document.write(parseInt("He was 40") + "<br>"); document.write("<br>"); document.write(parseInt("10",10)+ "<br>"); document.write(parseInt("010")+ "<br>"); document.write(parseInt("10",8)+ "<br>"); document.write(parseInt("0x10")+ "<br>"); document.write(parseInt("10",16)+ "<br>");
輸出結果:
10 10 34 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
【推薦學習:javascript高級教程】