如果你想向下取整一個數字,可以使用 JavaScript 中的 Math.floor()
函數。Math.floor()
會將一個數字向下舍入為最接近的小于等于它的整數。
以下是 Math.floor()
的基本用法:
Math.floor(number)
其中,number
是要進行向下取整的數字。
下面是一些示例:
console.log(Math.floor(3.4)); // 輸出: 3
console.log(Math.floor(3.9)); // 輸出: 3
console.log(Math.floor(-3.4)); // 輸出: -4
console.log(Math.floor(-3.9)); // 輸出: -4
在上述代碼中,我們使用 Math.floor()
對不同的數字進行了向下取整操作。可以看到,不論小數部分是多少,Math.floor()
都會將數字向下取整為小于等于它的整數。
需要注意的是,Math.floor()
函數返回的是一個整數,而不是保留小數位的結果。如果需要保留特定小數位數的精度,請使用其他方法,如 toFixed()
方法。
var num = 3.14159;
console.log(num.toFixed(2)); // 輸出: "3.14"
在上述代碼中,使用 toFixed(2)
將 num
的小數部分保留兩位,并返回一個字符串結果”3.14″。
這樣,你就可以根據需要使用 Math.floor()
函數進行向下取整,并結合其他方法來實現更精確的數值處理。