Reputation: 13
I need to check POST value is numeric and well formatted. My expected format is
number.number
1.0
11.5
If POST value comes without .(DOT)
only 1
then I would want that php convert that to 1.0
I tried this code but it doesn't work.
$foo = '2';
$foo = preg_match('/\\d{2}\\:\\d{2}\\.\\d{2}/', $foo);
Thanks :)
Upvotes: 1
Views: 4717
Reputation: 68
Working code
//$value = '22';
$value = $_POST["input_value"];
if (is_numeric($value)) {
$new_value = number_format($value, 1);
} else {
$new_value = "$value is not numeric. <br>";
}
echo $new_value;
Upvotes: 1
Reputation: 1139
You basically want to check if the variable from the POST array is a float/double or not (float/double is a type of number in the format of x.x).
Cheking if a string is a float/double number
To do that, use this php built-in function: is_double or more accurate:is_float, that will tell you if the string is a float/double.
Checking if a string is an integer and converting it to a double/float value
If it's not a double, check if it's an integer (regular number): is_int, and if it's indeed an int, cast it to double by using number_format
, look at the usage here: integer to double/float in php.
Example
$final_value;
$value = $_POST["wanted_value"];
if (is_float($value))
{
$final_value = $value;
}
else if (is_int($value))
{
$final_value = number_format($value, 1); // or 2 instead of 1 (2.0 or 2.00)
}
else
{
$final_value = "ERROR";
}
Hope this helps!
Upvotes: 0