Regex int or float

My regular expression will not work with a single digital number

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

I need it to work with unsigned numbers:

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

The number before the fraction can be 1-7 digits; after the fraction 1-2 digits.

Thanks you!

+3
source share
2 answers

You indicate that there should be 1-7 digits, then an optional decimal point, then another 1-2 digits. Try:

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

Please note that this does not allow trailing decimal places (ie "1."). If you want to allow this, this should work:

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

Make the decimal point and the numbers after it optional. eg.

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

, 1 - 7 , 1 - 7 , , 1 2 , , , , .

+1

Source: https://habr.com/ru/post/1757998/


All Articles