JS中的取整

JS中的取整

Math.ceil()——>天花板,向上取整

  -9 ——> 0 ——> 9,沿着这个方向无论正负都向上取整。

Math.floor()——>地板,向下取整

  -9 <—— 0 <—— 9,沿着这个方向无论正负都向下取整。

如何像其它语言那样向零取整

  先给Function.prototype添加method()方法使得该方法对所有函数可用:

1
2
3
4
Function.prototype.method=function(name,func){
this.prototype[name]=func;//方法调用模式,this绑定到该对象,即Function,再更新Function对象新增新的name属性
return this;
}

  然后给Number.prototype添加向零取整方法interger(),具体如下:

1
2
3
4
Number.method("integer",function(){
return Math[this<0 ? "ceil" : "floor"](this);
});
alert((-5.9).integer());

Math.round()——>把一个数字四舍五入为最接近的整数

  正数很正常:5.4——>5 , 5.5——>6
  负数有点小注意:-5.4——>-5, -5.5——>-5 , -5.51——>-6

文章目录
  1. 1. JS中的取整
    1. 1.1. Math.ceil()——>天花板,向上取整
    2. 1.2. Math.floor()——>地板,向下取整
    3. 1.3. 如何像其它语言那样向零取整
    4. 1.4. Math.round()——>把一个数字四舍五入为最接近的整数
,