What I want to do is determine if a string is numeric. I would like to know what people think about the two solutions I am trying to decide between (OR if there is a better solution that I have not found yet). The parseInt function is not suitable because it will return an integer value for a parameter like "40 years old". The two solutions I am deciding between are:
Use Integer.valueOf开发者_如何学Python() with try catch
function isNumeric(quantity)
{
var isNumeric = true
try
{
Integer.valueOf(quantity)
}
catch(err)
{
isNumeric = false
}
return isNumeric
}
Or check each character individually
function IsNumeric(quantity)
{
var validChars = "0123456789";
var isNumber = true;
var nextChar;
for (i = 0; i < quantity.length && isNumber == true; i++)
{
nexChar = quantity.charAt(i);
if (validChars.indexOf(nextChar) == -1)
{
isNumber = false;
}
}
return IsNumber;
}
I would have thought there would be a simpler solution than both of these though. Have I just missed something?
NOTE: I am using jQuery aswel so if there is a jQuery solution that that would be sufficient
I had to do something like you want, but I needed to verify if a variable contained a number without knowing its type, it could be a numeric string (considering also exponential notation, etc.), a Number object, basically anything.
And I had to take care about implicit type conversion, for example !isNaN(true) == true
was not good.
I ended up writing a set of 30+ unit test that you can find here, and I use the following function, that passes all my tests:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Why not isNaN(obj)
?
function IsNumeric (value) {
return (!((isNaN(value)) || (value.length == 0)));
}
how about a regex?
function IsNumeric(string) {
return string.match(/^\d+$/) !== null;
}
(not tested or very defensive, but you get the point)
If you are only testing strings, why not let any string use the method?
String.prototype.isNumeric= function(){
return parseFloat(this)== this;
}
This would work for most values
function isNumericString(s)
{
return !!s && !isNaN(+s);
}
generally unary + is the best way to convert to number. no base issue, no dangling non digit problem.
I suppose you could use a regular expression to validate the input, but I honestly don't see what's wrong with the first one.
Here is my solution with parseInt that will work:
var str = "40 years old";
var isNumeric = parseInt(str) == str ? true : false;
精彩评论