JavaScript取整数

JavaScript取整数的方法

1、舍弃小数部分,保留整数部分:parseInt()

示例:
//取整
function getResult(5 / 2)
return parseInt(5 / 2);

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

示例:
// 向上取整
var ceil = Math.ceil(5 / 2)
console.log('++++++++++', ceil) // 3

3、四舍五入:Math.round()

示例:
// 四舍五入
var round1 = Math.round(5 / 2),
round2 = Math.round(10 / 3)
console.log('**', round1) // 3
console.log('**', round2) // 3

4、向下取整:Math.floor()

示例:
// 向下取整
var floor = Math.floor(5 / 2)
console.log('----------', floor) // 2

猜你喜欢

转载自blog.51cto.com/14889696/2515243