TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Adventures in JavaScript number parsing

15 pointsby tjsnyderabout 15 years ago

5 comments

ionfishabout 15 years ago
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 <i>that</i> verbose.<p>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.
Kilimanjaroabout 15 years ago
I don't like abusing String prototype but:<p><pre><code> String.prototype.toInt=function(){ return parseInt(this,10) } </code></pre> then:<p><pre><code> "08".toInt() // ==&#62; 8</code></pre>
评论 #1341224 未加载
ck2about 15 years ago
I wonder what made the original coder on javascript assume that base10 should not ALWAYS be the default unless told otherwise.<p>At least all the different browsers' versions of javascript are consistent about that (right?)
评论 #1340986 未加载
cnlwsuabout 15 years ago
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.
DCoderabout 15 years ago
Well, it also parses hex numbers prefixed with 0x... Hard to be surprised after the first time you get tripped by it.