I want to convert a string into a number in Node. It should reject (by throwing an error) any string that isn't a number, including strings like "0x1" and "NaN" and anything else that isn't (off the top of my head so forgive me) /\d+(\.\d+)?/. How do I do it?
-
Show this thread
-
Gary Bernhardt Retweeted Eric Weinstein (エリック)
Gary Bernhardt added,
Eric Weinstein (エリック) @ericqweinsteinReplying to @garybernhardt`Number()`, `parseInt()`, `parseFloat()`, `~~`, and `+` all have pseudo-intelligent (read: dumb) behaviors that will thwart you here. AFAIK (and alas), I think a regular expression (throwing on failure to match) is your best bet. Ugh, sorry.3 replies 2 retweets 27 likesShow this thread -
From the replies, the answer to this seems to be: "Most systems written in JavaScript don't bother with a safe way to parse a number from a string. If you try to parse a number from a buggy string that's not a number, you'll get NaN and it will propagate through the system."
1 reply 3 retweets 15 likesShow this thread -
This is the same problem that exists with null etc. A bug causes an unexpected value (null/undefined/NaN/etc.) Ideally you crash immediately; then the traceback shows where the problem is. But often, that value propagates through the system and causes distant, confusing failures.
4 replies 7 retweets 41 likesShow this thread -
Replying to @garybernhardt
At least TypeScript can help protect you from null & undefined. Nothing can save you from NaN
1 reply 1 retweet 4 likes -
Replying to @sgrif
Ha... I saw this tweet come in as I was searching for "can TypeScript exclude NaN from a number value's type?" The answer is "no", but there's an open issue for it!https://github.com/Microsoft/TypeScript/issues/28682 …
1 reply 0 retweets 2 likes
I still think it's amusing that the type of "not a number" is "number"
-
-
Thanks. Twitter will use this to make your timeline better. UndoUndo
-
Loading seems to be taking a while.
Twitter may be over capacity or experiencing a momentary hiccup. Try again or visit Twitter Status for more information.