Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for positive decimal number with 0, 1 or 2 decimal places

Tags:

regex

Please help me make regular expression for positive decimal number with 0, 1 or 2 decimal places. It must allow comma and dot. For example it must allow:

0,01
0.01
0,1
1
1.1
1,11

but not allow:

-1
0.0
0,00
.01
0
1,111
1.111

I have this /(^\d*(?:\.|\,)?\d*[1-9]+\d*$)|(^[1-9]+\d*(?:\.|\,)\d*$)/ but I can`t find how to disallow more than 2 decimal places.

UPDATE I must reject 0.0, 0 and etc.

like image 782
Pavel F Avatar asked Oct 26 '25 06:10

Pavel F


2 Answers

Edit 2: now disallows exactly 0,0.0, etc.

This matches at least one digit before the decimal place, followed by an optional decimal place, followed by 0-2 digits.

The negative lookahead looks for any flavor of absolute zero and prevents a match.

^(?!0*[.,]0*$|[.,]0*$|0*$)\d+[,.]?\d{0,2}$

This is the raw regex, so you'll need to escape it appropriately for your language. (For example, in some languages you need to double the \ slashes as \\.

/^(?!0*[.,]0*$|[.,]0*$|0*$)\d+[,.]?\d{0,2}$/
like image 124
agent-j Avatar answered Oct 28 '25 21:10

agent-j


What you've got so far seems unnecessarily complicated to me. How about just

/^\d+([.,]\d{0,2})?$/

This is correct for every test case in the OP except for:

0.0
0,00
0

I don't see why you'd reject these.

like image 33
Matt Ball Avatar answered Oct 28 '25 20:10

Matt Ball