-1

I'm trying to make validation number with format x or x.xx (4 or 4.21). The format I managed to use regex for the x (single digit) is \ b \ d \ b. For x.xx format (two decimal places) I haven't found the regex pattern yet

$tes = 1;
if(!preg_match('\b\d\b', $tes)){
    echo 'right format';
 }else{
    echo 'not right';
 }
Wimanicesir
  • 4,606
  • 2
  • 11
  • 30
Newbie 123
  • 254
  • 4
  • 19

1 Answers1

0

For x.xx format (two decimal places)

If I understand correctly, you want to take exactly one number before point and two numbers after point. So, I suggest the following regex.

^\d(?:\.\d{2})?$

Details:

  • ^\d: always start with number
  • (?:\.\d{2}): this is optional. After the first number, we have exactly .xx
  • ?$: we take as many cases as possible

Demo

Thân LƯƠNG Đình
  • 3,082
  • 2
  • 11
  • 21