I need a function to check if number have 2 decimals or not.
For example:
$number = '1.00'; // Valid
$number2 = '1'; // Not valid
$number3 = '1.000' //Not valid
Why would you not just force them to have 2 decimals using something like this
$original = 2;
$float = number_format($number, 2);
// echo $float = 2.00
I guess if you need to enforce that a float only has 2 decimals you could do something like the following.
$numbers = array(2.453, 3.35, 2.53, 1.636);
foreach($numbers as $number) {
if(strpos($number, '.') !== false) {
if(strlen($parts[1]) == 2) {
echo $number .' is valid!';
} else {
echo $number .' is NOT valid!';
}
}
}
The above is one way to accomplish this but there are many others. You could use array_map or array_filter and you could also use math such as the following
$numbers = array(2.453, 3.35, 2.53, 1.636);
$valid_numbers = array_filter($numbers, function($number) { return strlen($number) - strpos($number, '.');
This may be a solution using preg_match_all
$re = "/^\\d+(?:\\.\\d{2})?$/m";
$str = "1.00\n13333.55\n1.000";
preg_match_all($re, $str, $matches);
echo '<pre>';
print_r($matches);
echo '</pre>';
Regex could be a solution since your numbers seem to be declared as strings.
Code :
Output :