js三个取整方法Math.ceil(),Math.floor(),Math.round()

Math.ceil()

该函数返回大于或等于一个给定数字的最小整数,即向上取整。

例:

conlose.log(Math.ceil(.95));   //结果为1
conlose.log(Math.ceil(4));   //结果为4
conlose.log(Math.ceil(7.004));   //结果为8
conlose.log(Math.ceil(-7.004));   //结果为-7

Math.floor()

该函数返回小于或等于一个给定数字的最大整数,即向下取整。

例:

console.log(Math.floor(45.95));  //结果为45
console.log(Math.floor(45.05));  //结果为45
console.log(Math.floor(4));    //结果为4
console.log(Math.floor(-45.05));  //结果为-46
console.log(Math.floor(-45.95));  //结果为-46

Math.round()

该函数返回的数字需四舍五入。但 .5 特殊

例:

console.log((Math.round(-20.5));  //结果为-20
console.log((Math.round(-20.51));  //结果为-21
x = Math.round(20.49);   //20
x = Math.round(20.5);    //21

猜你喜欢

转载自blog.csdn.net/woai_mihoutao/article/details/123295862