JS小数点怎么取整?

JavaScript022

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(向下取整)

一、小数转为整数

floor:下退 Math.floor(12.9999) = 12 ceil:上进 Math.ceil(12.1) = 13round: 四舍五入 Math.round(12.5) = 13 Math.round(12.4) = 12

二、小数位数控制

保留到整数:exam = Math.round(exam)

保留一位小数:exam = Math.round(exam * 10) / 10

保留二位小数:exam = Math.round(exam * 100) / 100

保留三位小数:exam = Math.round(exam * 1000) /1000

其它依次类推。