Adventures in JavaScript number parsing
mir.aculo.us
mir.aculo.us
A couple of other odd cases: +[] evaluates to 0, while +{} evaluates to NaN (parseInt([], 10) evaluates to NaN). +new Date evaluates to the integer representation of the current Unix timestamp; parseInt(new Date, 10) evaluates to NaN.
String.prototype.toInt=function(){ return parseInt(this,10) }
then: "08".toInt() // ==> 8 String.prototype.toInt = function (base) {
if (typeof base == 'undefined') base = 10;
return parseInt(this, base);
}
Smart defaults are always best, but there's no real need to handicap the users of your API.At least all the different browsers' versions of javascript are consistent about that (right?)
irb(main):002:0> "08".to_i => 8 irb(main):003:0> "08".to_i(8) => 0
ruby-1.8.7-p249 > nil.to_i
=> 0
ruby-1.9.2-head > nil.to_i
=> 0