I am passing in a parameter called value. I\'d like to know if value is a float. So far, I have the following:
if (!isNaN(value))
{
alert(\'this is a num
You can use the parseFloat
function.
If the value passed begins with what looks like a float, the function returns the value converted to a float, otherwise it will return NaN.
Something like:
function beginsWithFloat(val) {
val = parseFloat(val);
return ! isNaN(val);
}
console.log(beginsWithFloat("blabla")); // shows false
console.log(beginsWithFloat("123blabla")); // shows true
To check if a string is a float (avoid int values)
function isFloat(n) {
if( n.match(/^-?\d*(\.\d+)?$/) && !isNaN(parseFloat(n)) && (n%1!=0) )
return true;
return false;
}
var nonfloat = isFloat('12'); //will return false
var nonfloat = isFloat('12.34abc'); //will return false
var float = isFloat('12.34'); //will return true