var num = -123.321;
alert(Math[num > 0 ? "floor" : "ceil"](num)); //-123
num = 123.321;
alert(Math[num > 0 ? "floor" : "ceil"](num)); //123
注意不能直接用ceil或floor。向上或向下在正数与负数的情况下会有不符合预期的结果。
var num = -123.321;
alert(Math.floor(num)); //-124
alert(Math.ceil(num)); //-123
alert(Math[num > 0 ? "floor" : "ceil"](num)); //-123
num = 123.321;
alert(Math.floor(num)); //123
alert(Math.ceil(num)); //124
alert(Math[num > 0 ? "floor" : "ceil"](num)); //123
这个坑是最近看《JavaScript语言精粹》时看到的,觉得不错,记录一下。
书中给出的代码更规范一些。
Function.prototype.method = function(name, func){
this.prototype[name] = func;
return this;
};
Number.method("integer", function(){
return Math[this > 0 ? "floor" : "ceil"](this);
});
alert(-123.321.integer()); //-123