1

The pattern

$test =  preg_match('/^(?=.\d)\d(?:\.\d\d)?$/', $_float1);

matches

0.25
2.55
1253.36
45.55

How to modify this to accept a comma in between the integer part? such as 1,253.36?

Murali Uppangala
  • 884
  • 6
  • 22
  • 49
  • 1
    Why did you set the JavaScript tag ? This looks more like PHP to me. – Denys Séguret May 06 '15 at 08:05
  • 1
    Potential duplicates: [this one](http://stackoverflow.com/questions/7199085/regex-for-optional-comma-separated-number-with-decimal-point) and [this one](http://stackoverflow.com/questions/20154386/regex-a-decimal-number-with-comma), but there are numerous other similar questions. – Didier L May 06 '15 at 08:13
  • @dystroy yes its php i will remove the tags! – Murali Uppangala May 06 '15 at 10:34

3 Answers3

2

You could use this pattern:

/^\d*(,?\d{3})*(\.\d+)?$/
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

You can use this regex:

^\d+(?:,\d{3})*(?:\.\d\d)?$

RegEx Demo

anubhava
  • 761,203
  • 64
  • 569
  • 643
1

I would've used this one:

/^\d{1,3}(?:(,?)\d{3}(\1\d{3})*)?(?:\.\d{2})?$/

Explained:

  • ^\d{1,3}: starts by 1 to 3 digits
  • (?:(,?)\d{3}(\1\d{3})*)?: [optional] repeat XXX or ,XXX patterns (only one of them, to exclude numbers like 11,111111)
  • (?:\.\d{2})?: [optional] exactly two decimal places
  • $: That's all folks

Matches:

1 - 12 - 123 - 1234 - 12345
1,234 - 12,345 - 123,456 - 1,234,567
1.23 - 12.34 - 123.45 - 1234.56 - 12345.67
1,234.56 - 12,345.67 - 123,456.78 - 1,234,567.89

Doesn't match:

.1 - .12 - .123
1.2 - 1.234 - 1.2345
12,34 - 123,45 - 1,2345 - 1,2,345 - 1234,567
12,34.56 - 123,45.67 - 1,2345.78

zessx
  • 68,042
  • 28
  • 135
  • 158