JS小数点怎么取整?

JavaScript06

JS小数点怎么取整?,第1张

1.丢弃小数部分,保留整数部分   eg:parseInt(5/2)

2.向上取整,有小数就整数部分加1  eg:Math.ceil(5/2)

3.四舍五入.  eg:Math.round(5/2)

4.向下取整  eg:Math.floor(5/2)

举例: aa=parseInt(5/2)

alert("取整"+aa)//2(丢掉小数部分)

bb=Math.ceil(5/2) alert("ceil"+bb)//3(向上取整)

cc=Math.round(5/2)alert("round"+cc)//3(四舍五入)

dd=Math.floor(5/2)alert("floor"+dd)//2(向下取整)

1.Math.floor()

例子:

function getFloor(x) {

return Math.floor(x)

} 如果你传递45.95 给getFloor()函数, 返回45如果传递的参数为-45.95, 返回-46.

2.Math.ceil()

例子:function getCeil(x) {

return Math.ceil(x)

} 如果你传递的参数是45.95 给函数 getCeil, 返回46如果传递的参数为-45.95, 返回-45.