Forum Moderators: coopster

Message Too Old, No Replies

Help with regular expression

Number with 2 decimal places max

         

Merganser

7:36 pm on Feb 13, 2010 (gmt 0)

10+ Year Member



I need a regular expression that I am having difficulty with. What I want is to be able to identify if a submitted form element (string) comprises a number with 2 decimal places max. However, I want the user to not have to enter a decimal at all. In other words, the following would match the regular expression.

3.14
0.
5
.47

The expression I have come up with is:

^[0-9]{0,2}\.[0-9]{0,2}$

However, this requires a decimal point which I do not want to be mandatory. What I really want to validate is a number with 1-2 digits if there is not a decimal point. But if there is a decimal point, 0-2 digits before and 0-2 digits after the decimal (although 0 before AND 0 afterwards, and any value representing zero should not be allowed - but I can perfom a separate check for this condition if necessary).

I feel like I need an "if" statement within my regular expression but I do not know how to accomplish that. Any help is appreciated.

jdMorgan

9:12 pm on Feb 13, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Something like:

^([0-9]{1,2}(\.[0-9]{0,2})?|[1-9]{0,2}\.[0-9]{1,2})$

if I understand your specifications above.

(Regex does not test the "value" -- only the "character set.")

Jim

Merganser

2:41 am on Feb 14, 2010 (gmt 0)

10+ Year Member



OK - I get it. Needed the pipe (|) for OR and use of the parentheses. I modified yours slightly and went with the following. Seems to produce the effect I wanted. Thanks!

^[0-9]{1,2}(\.[0-9]{0,2})?$|^\.[0-9]{1,2}$