JavaScript四種數值取整方法


一、Math.trunc()

1.定義

Math.trunc()方法去除數字的小數部分,保留整數部分。

2.語法

Math.trunc(value)

3.示例

console.log(Math.trunc(2.01)); // 2
console.log(Math.trunc(2.9)); // 2
console.log(Math.trunc('0.22')); // 0
console.log(Math.trunc(-1.22)); // -1
console.log(Math.trunc(-1.56)); // -1
console.log(Math.trunc(true)); // 1
console.log(Math.trunc(undefined)); // NaN

二、Math.round()

1.定義

Math.round()方法返回一個數字四舍五入后的整數部分。

2.語法

Math.round(value)

3.示例

console.log(Math.round(2.01)); // 2
console.log(Math.round(2.9)); // 3
console.log(Math.round('0.22')); // 0
console.log(Math.round(-1.22)); // -1
console.log(Math.round(-1.56)); // -2
console.log(Math.round(true)); // 1
console.log(Math.round(undefined)); // NaN

三、Math.ceil()

1.定義

Math.ceil()方法返回一個大於或等於數字的最小整數,即向上取整。

2.語法

Math.ceil(value)

3.示例

console.log(Math.ceil(2.01)); // 3
console.log(Math.ceil(2.9)); // 3
console.log(Math.ceil('0.22')); // 1
console.log(Math.ceil(-1.22)); // -1
console.log(Math.ceil(-1.56)); // -1
console.log(Math.ceil(true)); // 1
console.log(Math.ceil(undefined)); // NaN

四、Math.floor()

1.定義

Math.floor()方法返回一個小於或等於數字的最小整數,即向下取整。

2.語法

Math.floor(value)

3.示例

console.log(Math.floor(2.01)); // 2
console.log(Math.floor(2.9)); // 2
console.log(Math.floor('0.22')); // 0
console.log(Math.floor(-1.22)); // -2
console.log(Math.floor(-1.56)); // -2
console.log(Math.floor(true)); // 1
console.log(Math.floor(undefined)); // NaN

JavaScript四種數值取整方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM