tags:

views:

50

answers:

2
+3  Q: 

regex int or float

Hi,

My regex won't work on single digit number

/^[0-9]{1,7}\.?[0-9]{1,2}$/

I need it to work on unsigned numbers:

1 (single digit numbers, without fractions) - currently it fails on them
1.0; 0.31 (floating point numbers)

Number before fraction can be 1-7 digits; after fraction 1-2 digits.

Thanks you!

+3  A: 

You're specifying that there must be 1-7 digits, then an optional decimal point, then 1-2 more digits. Try:

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

Note that this doesn't allow trailing decimal places (i.e. "1."). If you want to allow that, this should work:

/^[0-9]{1,7}(?:\.[0-9]{0,2})?$/
Graeme Perrow
At the same time, the second expression allows numbers with 8-9 digits.
quantumSoup
@Air fixed that.
Artefacto
+1  A: 

Make the decimal point and the digits after it optional. e.g.

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

That way you can have a either 1 - 7 digits or 1 - 7 digits followed by a decimal point followed by 1 or 2 digits but if you had digits followed by a decimal point but no further digits that would not be valid.

mikej