2

how can i check number is valid with below string.

last 2 digit may content decimal value or may not.

below are the code which i have already tried with preg_match but couldn't get any success

$newPrice = "2,264.00"; or //  $newPrice = "264.00"; 

 if (!preg_match('/^[+-][0-9]+(\,[0-9]+)?%?$/', $newPrice))
{                
    echo "not valid";
 }else{                    
       echo "valid";
}
exit();

above both price is correct as per allowed format.

liyakat
  • 11,825
  • 2
  • 40
  • 46

3 Answers3

6

The regex has 3 parts;

[0-9]{1,3}     1-3 digits
(,[0-9]{3})*   An optional repeated part of a comma + 3 digits
(\.[0-9]{2})?  An optional part of a decimal dot and 2 digits

This can be written as;

/^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]{2})?$/
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
1

try this

^[+-]?[\d\,]+\.?\d+?

this will match values like :

222,222,264.00
+2,424,24.34
-264
264.00

demo

aelor
  • 10,892
  • 3
  • 32
  • 48
0

Use this regex:

[0-9,]+(?:\.[0-9]*)?

Regular expression visualization

Debuggex Demo

Amit Joki
  • 58,320
  • 7
  • 77
  • 95