javascript取整方法floor、round、ceil

  •   
  • 3314
  • jQuery
  • 4
  • super_dodo
  • 2015/04/27

javascript取整函数有哪些,这些函数,对于脚本使用者可能会经常要用到,在这里为大家一一列出。
1.字符串转化为整形:parseInt(str);如parseInt("7.6")**返回7
2.向上取整,有小数就整数部分加1:Math.ceil(number) ;如Math.ceil(7.6) **返回8
3.向下取整,舍去小数部分 : Math.floor(number) ;如Math.floor(7.6) **返回7
4.四舍五入 :Math.round(number) ;如Math.round(3.4) **返回3, 但是Math.round(3.5)**返回4

floor向下取整:

Math.floor(0.20); // 0
Math.floor(0.90); // 0
Math.floor(-0.90); // -1
Math.floor(-0.20); // -1

round四舍五入

Math.round(0.2) // 0
Math.round(0.9) // 1
Math.round(-0.9) // -1
Math.round(-0.2) // 0

ceil向上取整

Math.ceil(0.2) // 1
Math.ceil(0.9) // 1
Math.ceil(-0.9) // 0
Math.ceil(-0.2) // 0
//1.丢弃小数部分,保留整数部分
parseInt(5/2)   	// 2

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

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

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

雪崩时,没有一片雪花觉得自己有责任。