Reputation: 23
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
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 stringUpvotes: 2