Why does 2.ceil() throws exception whereas 2.3.ceil() returns 3 in prototype.js?
To make it more generic ... I change the prototype of Number object in Javascript by doing this
Number.prototype.ceil = function() { return Math.ceil(this); };
Now 2.3.ceil() returns 3 and 2.ceil() throws exception. But if开发者_运维知识库 I do b=2 and then do b.ceil() , it works fine!! So, basically it is still a problem of javascript.
The method is Math.ceil
, it's not an instance method.
var b = 2;
console.log(Math.ceil(b));
b = 2.3;
console.log(Math.ceil(b));
It looks like it would be trivial to create a prototype method that can do this:
Number.prototype.ceil = function() {
return Math.ceil(this);
};
console.log(2.3.ceil());
It also looks like JavaScript reserves the first decimal in numeric literals for adding decimals to the number. This is a language feature. To get around this, you need two decimals:
2.ceil(); // does not work
2.3.ceil(); // does work
2..ceil(); // does work
You shouldn't be able to do any of that, unless you have some kind of framework or something that is prototyping .ceil() as a method, in which case it is probably prototyping it as a method on strings. IOW .ceil() isn't a native javascript method.
Javascript's native "round up" method .ceil() works by using the Math object like
alert(Math.ceil(2.3));
2.ceil()
looks like it'd be a syntax error. (The interpreter might be confused about the dot -- it'd try to interpret the dot as part of the number.)
See if 2..ceil()
(note the double dots) or (2).ceil()
works for you.
精彩评论