您的位置:首頁技術文章
文章詳情頁

JavaScript 如何刪除小數點后的數字

瀏覽:5日期:2022-06-13 09:14:59

使用 Math.trunc() 函數刪除小數點后的數字,例如 Math.trunc(1.37)。 Math.trunc() 函數刪除小數位并返回數字的整數部分。

const num = 124.567;const removeDecimal = Math.trunc(num); // 124console.log(removeDecimal);const roundDown = Math.floor(num); // 124console.log(roundDown);const roundNearestInteger = Math.round(num); // 125console.log(roundNearestInteger);const roundUp = Math.ceil(num);console.log(roundUp); // 125

我們的第一個示例使用 Math.trunc 函數。

該函數不會以任何方式對數字進行四舍五入,它只是移除小數部分并返回整數。

看下面的示例

console.log(Math.trunc(-1.37)); // -1console.log(Math.trunc(2.0)); // 2console.log(Math.trunc(5.35)); // 5

下一個可能的情況是通過向下舍入來刪除小數點后的數字。 使用 Math.floor 函數。

該函數返回小于或等于提供的數字的最大整數。 這里有些例子。

console.log(Math.floor(-1.37)); // -2console.log(Math.floor(2.6)); // 2console.log(Math.floor(5.35)); // 5

下一個示例顯示如何使用 Math.round 函數將數字四舍五入到最接近的整數。 這里有些例子。

console.log(Math.round(-1.37)); // -1console.log(Math.round(2.5)); // 3console.log(Math.round(5.49)); // 5

最后一個示例顯示了如何使用 Math.ceil 函數通過四舍五入來刪除小數點后的數字。

Math.ceil 函數總是向上進入一個數字。 這里有些例子。

console.log(Math.ceil(-1.99)); // -1console.log(Math.ceil(2.01)); // 3console.log(Math.ceil(5.49)); // 6

如果您想簡單地刪除小數點后的數字,而不以任何方式進行四舍五入,請使用 Math.trunc 函數。

到此這篇關于JavaScript 刪除小數點后的數字的文章就介紹到這了,更多相關js刪除小數點后的數內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: JavaScript
国产综合久久一区二区三区