user3811320
user3811320

Reputation: 23

Regular expression for numbers with maximum 4 decimal values

I need a regular expression where a number can accept maximum up to 4 decimal values.

Valid values:

1.2222
0.50
.50

Invalid values:

56.56666666
12.

Currently the regular expression I am using is ^\d+\.?\d{0,4}$, this is not working in case of .50 but its working for 0.50.

Can some one please help me out.

Upvotes: 1

Views: 170

Answers (2)

Uri Y
Uri Y

Reputation: 850

Try the following regex:

\d*\.\d{1,4}\b

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626952

To match the number formats you specified, use

^(?=.)\d*(?:\.\d{1,4})?$

See the regex demo.

Details

  • ^ - start of string
  • (?=.) - there must be at least 1 char in the string (or (?!$) - no end of string right after the start of string - no empty string allowed)
  • \d* - 0+ digits
  • (?:\.\d{1,4})? - an optional sequence of
    • \. - a dot
    • \d{1,4} - 1 to 4 digits
  • $ - end of string

Upvotes: 2

Related Questions