There may be a simpler way but I didn’t come across one except this handy function when dealing with decimal numbers.
////////////////////////////////////////////////////////////////////////////////////////////// //is_wholeNumber(string $value) //Returns TRUE if a WHOLE NUMBER //Returns FALSE if anything else (Float, String, Hex, etc) ////////////////////////////////////////////////////////////////////////////////////////////// function is_wholeNumber($value) { if(preg_match ("/[^0-9]/", $value)) { return FALSE; } return TRUE; }
There is also ctype_digit but this seems to return false when using addition like so:
$numeric_string = '1'+'1'; $integer = 1+1; if(ctype_digit($numeric_string)) { echo "true";} else { echo "false"; } // false if(ctype_digit($integer)){ echo "true";} else { echo "false"; } // false if(is_numeric($numeric_string)){ echo "true";} else { echo "false"; } // true if(is_numeric($integer)){ echo "true";} else { echo "false"; } // true
Both equal 2 yet ctype_digit returns false? , is_numeric works here but as i’m dealing with decimal places this returns true when it is not a whole number.
Credit for the function due to http://davidwalsh.name/php-validatie-numeric-digits
Easier way to have wrote the function would have been …
function is_wholeNumber($value)
{
return !preg_match (“/[^0-9]/”, $value);
}
Thanks James I did write this post quite a while ago you solution is much simpler!