I’m trying to write a RegEx to validate a floating point number. Here’s what I’ve managed thus far:
/^[-+]?[1-9]\d{0,2}(\.\d{1,1})?/
The number is valid if:
- Either positive or negative
- Max of 2 digits (tens or hundreds)
- Hundredths digit can’t 0 (only 1-9)
- Scale is max of 1
- Decimal value can be 0 or 5 or none at all
So these numbers would be valid, for ex:
- 1.5
- -1.5
- 17.5
- 15
- -3
- 30.5
These numbers would be invalid, for ex:
- 1.57
- 3041.5
- 17.59
- 915
- -1.56
- 05.0
As I said in the comments – your first non-zero digit will count, then you add two more – which will now allow three-digit numbers like
915. To solve this the regexp way (with your testcases):I use negative lookahead
(?!0)to make sure the first digit is not a zero, then just require the desired number of digits. It also allows0.5and similar through the|0disjunction. If you prefer.5, it’ll be this:If you want to disallow
3.0(allowed by your rules) and only allow3(as you imply in the examples), replace the last part:However, this is much less readable than @Arkku’s nice
Float(number); use regexps if you really need them.