PHP Allow only numbers with 2 decimals

2.1k views Asked by At

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
6

There are 6 answers

0
Falt4rm On BEST ANSWER

Regex could be a solution since your numbers seem to be declared as strings.

Code :

<?php
 $re = "/(\d\.\d{2})(?!\d)/"; 
$array_input = array('1.00', '1', '1.000');

foreach($array_input as $row)
{
    if(preg_match($re, $row, $matches) == 0)
        echo $row . " isn't a valid value with 2 decimals only. <br>";

    else
        echo $row . " is valid. <br>";
}
?>

Output :

1.00 is valid.
1 isn't a valid value with 2 decimals only.
1.000 isn't a valid value with 2 decimals only. 
2
Joseph Crawford On

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, '.');
0
Ybrin On

You can check it like that:

$str = "1.23444";
print strlen(substr(strrchr($str, "."), 1));

You would have to convert your variable to a String, but this is not a big problem. Do it like that:

$d = 100.0/81.0;
$s = strval($d);
0
Gregory Wullimann On

You can do something like this:

if(strlen(substr(strrchr($number, "."), 1)) == 2){
    echo "valid";
}else{
    echo "not valid";
}
0
A l w a y s S u n n y On

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: https://regex101.com/r/nB7eC4/1

CODE: http://codepad.viper-7.com/49ZuEa

0
William Gu On
function check_decimals($input, $number_of_decimals) 
{
   if(strlen(substr(strrchr((string)$input, "."), 1)) == $number_of_decimals) 
   {
       return TRUE;
   }
   else {
       return FALSE;
   }
}

check_decimals("1.000", 2);