

Adventures in JavaScript number parsing - tjsnyder
http://mir.aculo.us/2010/05/12/adventures-in-javascript-number-parsing/

======
ionfish
The problem with replacing parseInt with the unary + operator is that they
don't have the same semantics. +"" evaluates to 0, while parseInt("", 10)
evaluates to NaN. Tricks like this are fine if you know that it won't matter
for your input, but generally speaking you're better off with parseInt and a
radix. Yes, it's unnecessarily verbose for the normal case, but it's not
_that_ verbose.

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.

------
Kilimanjaro
I don't like abusing String prototype but:

    
    
      String.prototype.toInt=function(){ return parseInt(this,10) }
    

then:

    
    
      "08".toInt() // ==> 8

~~~
jherdman
Hmm... I think you might find this a little more flexible in the long run:

    
    
        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.

------
ck2
I wonder what made the original coder on javascript assume that base10 should
not ALWAYS be the default unless told otherwise.

At least all the different browsers' versions of javascript are consistent
about that (right?)

~~~
madrobby
Yes, they should be consistent. Afaik. Thank science that other languages are
better in that regard (here's Ruby):

irb(main):002:0> "08".to_i => 8 irb(main):003:0> "08".to_i(8) => 0

~~~
warfangle
Yet ruby has its own idiosyncrasies, with nil.id evaluating to 4.

~~~
jherdman
FYI:

    
    
        ruby-1.8.7-p249 > nil.to_i
         => 0
    
        ruby-1.9.2-head > nil.to_i
         => 0

------
cnlwsu
This is not unique to Javascript. To a Java programmer this behavior seems
natural(octal literals lead with a 0) and not really worthy of a angry blog
post.

------
DCoder
Well, it also parses hex numbers prefixed with 0x... Hard to be surprised
after the first time you get tripped by it.

