Wednesday 17 December 2008

Javascript parseInt, parseFloat, decide on data type

I was facing an issue today whereby I need to accept a value from an input control, but not knowing what it contained - i.e. a number, a floating point number (decimal) or a string, but I needed to perform maths on it.

With some help of some friends over at forums.asp.net, I came up with the following. You pass it your value, and it will send back the right data type to use on mathematical operations like "+" which normally concatenates strings instead of adding numbers as strings.


function parseValues(aValue)
{
if(isNaN(aValue))
{
return aValue;
}
else
{
if(aValue.indexOf(".")>0)
{
return parseFloat(aValue);
}
else
{
return parseInt(aValue);
}
}
}

No comments:

Post a Comment