您的位置:首页 > Web前端 > JavaScript

javascript中的Math.ceil() 、Math.floor() 、Math.round() 三个函数

2016-07-30 13:31 609 查看
首先还是看看《The Definitive Guide, 4th Edition》书中对三个函数的的定义。

Math.ceil(x): round a number up

Arguments: Any numeric value or expression

Returns: The closest integer greater than or equal to x.

-----------------------------------------------------------------------------------------------------

Math.floor(x): round a number down

Arguments: Any numeric value or expression

Returns: The closest integer less than or equal to x.

-----------------------------------------------------------------------------------------------------

Math.round(x): round to the nearest integer

Arguments: Any number.

Returns: The integer closest to x.

 

通过对三个函数的原型定义的理解,其实很容易记住三个函数。

1. Math.ceil() 用作向上取整。

2. Math.floor() 用作向下取整。

3. Math.round() 用作四舍五入取整。

 

最后通过一个具体应用,进一步加深对三个函数的印象:

假设现在我要做一个Web Puzzle,需要获取一个指定范围的随机数,下面我会编写一个自定义函数getRangeRandom(m, n, t)。

<script type="text/javascript">
/*
** 函数功能: 获取指定范围的随机数
*/
function getRangeRandom(m, n, t)
{
var seed =0;
switch(t)
{
// 随机数范围: m <= seed < n
case0:
seed = m + parseInt(Math.random() * n);
break;

// 随机数范围: m <= seed < n
case1:
seed = m + Math.floor(Math.random() * n);
break;

// 随机数范围: m < seed <= n
case2:
seed = m + Math.ceil(Math.random() * n);
break;

// 随机数范围: m <= seed <= n
case3:
seed = m + Math.round(Math.random() * n);
break;
}

return seed;
}
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript 函数