I have a simple function which checks if a value is a number and if that number is less than 0.
function check_number($value){
if(!is_numeric(strval($value))){
return "value must be whole or decimal";
} else {
if($value < 0){
return "value must be bigger than 0";
}
}
return "successful value";
}
This functions works all well and good, until special numbers are passed in such as:
These values will still make the function return "successful value".
How can I make these special numbers not return a false positive in my case.
Thanks.
function check_number($value){
if (!is_numeric($value)) {
return "That is not a number";
}
if ($value < 0) {
return "value must be bigger than 0";
}
if(!ctype_digit(str_replace('.', '', $value))){
return "value must be whole or decimal";
}
return "successful value";
}
You have peculiar requirements. Your definition of a number differs from PHP's - 4.1e7 is a number, just not one formatted in a way you like. So you need to look at the number as it appears - as a string.
Check if value is less than 0 first, because later we won't distinguish between a minus sign and any other character.
Count dots in the number string.
If more than 1 dot, return fail.
If just 1 dot, str_replace it out and continue.
Finally, use ctype_digit on the remaining string.
Change
if(!is_numeric(strval($value))){
into
$value = trim($value, "0"); // get value as string and remove leading and trailing zeroes
$value_float = ltrim(floatval($value), "0"); // get float value as string and remove leading zero
if($value !== $value_float){
or to make it compacter
if(trim($value, "0") !== ltrim(floatval($value), "0")){
to check whether the numerical representation is still the same after stringifying.