使用 Math.trunc() 函數刪除小數點后的數字,例如 Math.trunc(1.37)。 Math.trunc() 函數刪除小數位并返回數字的整數部分。 const num = 124.567;const removeDecimal = Math.trunc(num); // 124console.log(removeDecima
使用 Math.trunc()
函數刪除小數點后的數字,例如 Math.trunc(1.37)。 Math.trunc() 函數刪除小數位并返回數字的整數部分。
const num = 124.567; const removeDecimal = Math.trunc(num); // 124 console.log(removeDecimal); const roundDown = Math.floor(num); // 124 console.log(roundDown); const roundNearestInteger = Math.round(num); // 125 console.log(roundNearestInteger); const roundUp = Math.ceil(num); console.log(roundUp); // 125
我們的第一個示例使用 Math.trunc 函數。
該函數不會以任何方式對數字進行四舍五入,它只是移除小數部分并返回整數。
看下面的示例
console.log(Math.trunc(-1.37)); // -1 console.log(Math.trunc(2.0)); // 2 console.log(Math.trunc(5.35)); // 5
下一個可能的情況是通過向下舍入來刪除小數點后的數字。 使用 Math.floor 函數。
該函數返回小于或等于提供的數字的最大整數。 這里有些例子。
console.log(Math.floor(-1.37)); // -2 console.log(Math.floor(2.6)); // 2 console.log(Math.floor(5.35)); // 5
下一個示例顯示如何使用 Math.round 函數將數字四舍五入到最接近的整數。 這里有些例子。
console.log(Math.round(-1.37)); // -1 console.log(Math.round(2.5)); // 3 console.log(Math.round(5.49)); // 5
最后一個示例顯示了如何使用 Math.ceil 函數通過四舍五入來刪除小數點后的數字。
Math.ceil 函數總是向上進入一個數字。 這里有些例子。
console.log(Math.ceil(-1.99)); // -1 console.log(Math.ceil(2.01)); // 3 console.log(Math.ceil(5.49)); // 6
如果您想簡單地刪除小數點后的數字,而不以任何方式進行四舍五入,請使用 Math.trunc 函數。
到此這篇關于JavaScript 刪除小數點后的數字的文章就介紹到這了,更多相關js刪除小數點后的數內容請搜索技圈網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持技圈網!
聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。