Jump to content

Preg_match for decimals?


woolyg

Recommended Posts

/^([0-9.]+)$/

 

Corbin, the problem with this pattern is that it will even satisfy 100.234

Here is my take:

 

$str = '1004325.23';
if (preg_match('#^\d+(?:\.\d{1,2})?$#', $str, $match)){
   echo $match[0] . ' is valid!';
} else {
   echo $str . ' is NOT valid!';
}

 

This pattern assumes:

a) no limit to the amount of numbers prior to a decimal point (if there even is a decimal with digits after it)

b) if there is a decimal, there is a minimum of 1 digit, and a maximum of 2 digits).. [if the OP only wants 2 digits after the decimal, change \d{1,2} to \d{2}]

 

Cheers,

 

NRG

or...

function is_valid($number){
if(is_numeric){
   list($nu,$de) = explode('.',$number);
   return (strlen($de) < 3 || !isset($de)) ? TRUE : FALSE;
}else{
   return FALSE;
}
}

 

this line:

if(is_numeric){

 

should be:

if(is_numeric($number)){

 

as is_numeric is a function call that requires a single argument. With your current code, an assumed constant 'is_numeric' error occurs.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.