使用 Math.trunc()
函數(shù)刪除小數(shù)點(diǎn)后的數(shù)字,例如 Math.trunc(1.37)。 Math.trunc() 函數(shù)刪除小數(shù)位并返回?cái)?shù)字的整數(shù)部分。
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
我們的第一個(gè)示例使用 Math.trunc 函數(shù)。
該函數(shù)不會以任何方式對數(shù)字進(jìn)行四舍五入,它只是移除小數(shù)部分并返回整數(shù)。
看下面的示例
console.log(Math.trunc(-1.37)); // -1 console.log(Math.trunc(2.0)); // 2 console.log(Math.trunc(5.35)); // 5
下一個(gè)可能的情況是通過向下舍入來刪除小數(shù)點(diǎn)后的數(shù)字。 使用 Math.floor 函數(shù)。
該函數(shù)返回小于或等于提供的數(shù)字的最大整數(shù)。 這里有些例子。
console.log(Math.floor(-1.37)); // -2 console.log(Math.floor(2.6)); // 2 console.log(Math.floor(5.35)); // 5
下一個(gè)示例顯示如何使用 Math.round 函數(shù)將數(shù)字四舍五入到最接近的整數(shù)。 這里有些例子。
console.log(Math.round(-1.37)); // -1 console.log(Math.round(2.5)); // 3 console.log(Math.round(5.49)); // 5
最后一個(gè)示例顯示了如何使用 Math.ceil 函數(shù)通過四舍五入來刪除小數(shù)點(diǎn)后的數(shù)字。
Math.ceil 函數(shù)總是向上進(jìn)入一個(gè)數(shù)字。 這里有些例子。
console.log(Math.ceil(-1.99)); // -1 console.log(Math.ceil(2.01)); // 3 console.log(Math.ceil(5.49)); // 6
如果您想簡單地刪除小數(shù)點(diǎn)后的數(shù)字,而不以任何方式進(jìn)行四舍五入,請使用 Math.trunc 函數(shù)。
到此這篇關(guān)于JavaScript 刪除小數(shù)點(diǎn)后的數(shù)字的文章就介紹到這了,更多相關(guān)js刪除小數(shù)點(diǎn)后的數(shù)內(nèi)容請搜索技圈網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持技圈網(wǎng)!