4 ms·
> If my "number" is in fact a string I'd like to get an error instead of a type conversion that hides this error. If you expect a number or a string, call pars
by jessedhillon 12y ago
> If my "number" is in fact a string I'd like to get an error instead of a type conversion that hides this error.
If you expect a number or a string, call parseInt() on your value and then isNaN() on that will tell you whether you have an error condition. Your code will be more understandable if you spend time parsing your inpt and explicitly casting to expected types, rather than papering over differences with ===
- robocat 12y agoWrong jessedhillon, becaue parseInt() is as quirky as == (this is JavaScript, remember!). parseInt('1 are you joking') returns 1. parseInt('077') returns 63 on some older browsers (get off my octal lawn). parseInt('0XALIC ACID') returns 10. parseInt(' -1e5') returns -1. And dealing with Integers in JavaScript is fraught with danger since browser JavaScript only really knows floating point numbers. e.g. parseInt('999999999999999999999999999999999999999999999999999999999999999999999999999999999') returns 1e+81... Smoke that! Edit: It is possible to build some reliable integer routines using logical operators (since they convert to unsigned integers to perform the operation) but one needs to understand the other underlying quirks to do so.
- UweSchmidt 12y agoYes, it's parseInt() plus some further checks if the results are within an expected range in my code. And overall being more verbose, explicit, and careful. And the occasional squinting eyes from the "Fry meme".
- LukeB_UK 12y agoParseInt accepts a second parameter for the radix, it's use is highly encouraged.