1. ## Validate number function

I have a function to check if a string (say the value of an input element) is a valid number. By valid number (I'm not a math whiz or anything) I mean something like -9999, 55000, 1.223523, 1.5. Something like '-9999LETTER' or 'l123494' would not be valid.

If I combined parseFloat and isNaN, with something like..

var isNumber = function(str) {
if (isNaN(parseFloat(str))) { return false; }
else { return true; }
}

Then parseFloat would obviously only extract the numbers from the string. Therefore if I did isNumber('555555555rrrrrrrrrrrrr') I would get a return value of true, since it only extracts the 555555555 via parseFloat, but the value ITSELF is not a valid number because of the r's.

Then I heard of the subtraction of zero to force it to be a number and changed my function like so...

var isNumber = function(str) {
if (isNaN(str-0)) { return false;}
else {return true;}
}

Edit:
Just optimized it so it would be a one-liner

function isNumber(str) { return !isNaN(str-0) }

isNumber('5555555555rrrrrrrr') would now return false which is exactly what I want.

I'm just wondering if there are any quirks there may be of my new function that subtractions 0 to try to convert it into a number or if there are any better ways of doing it.

Thanks.

2. str * 1 does the same thing ... if the str is not a number then the product is NaN, hence isNaN = true.

3. Instead of using those hacks, properly cast the value to a number instead. If it's not a proper number it will return NaN.

The other benefit is the code becomes more unstastandable.

Code Javascript:
`function isNumber(str) { return !isNaN(Number(str)) }`

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•