4 ms·
Adventures in JavaScript number parsing
- ionfish 16y agoThe 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.
- ck2 16y agoI 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 16y agoYes, 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
- Kilimanjaro 16y agoI don't like abusing String prototype but: String.prototype.toInt=function(){ return parseInt(this,10) } then: "08".toInt() // ==> 8
- jherdman 16y agoHmm... 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.
- DCoder 16y agoWell, it also parses hex numbers prefixed with 0x... Hard to be surprised after the first time you get tripped by it.
- cnlwsu 16y agoThis 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.