I got this expression from stackoverflow itself - /^\d+(\.\d{0,9})?$/.
It takes care of:
2
23
23.
25.3
25.4334
0.44
but fails on .23. Can that be added to the above expression, or something that would take care of all of them?
I got this expression from stackoverflow itself - /^\d+(\.\d{0,9})?$/.
It takes care of:
2
23
23.
25.3
25.4334
0.44
but fails on .23. Can that be added to the above expression, or something that would take care of all of them?
This will capture every case you posted as well as .23
Limit to 9 decimal places
var isDecimal = string.match( /^(\d+\.?\d{0,9}|\.\d{1,9})$/ );
No decimal limits:
var isDecimal = string.match( /^(\d+\.?\d*|\.\d+)$/ );
3.141592653589793238462643383279502884197169399375105820974 ;~)This covers all your examples, allows negatives, and enforces the 9-digit decimal limit:
/^[+-]?(?=.?\d)\d*(\.\d{0,9})?$/
Live demo: https://regexr.com/4chtk
To break that down:
[+-]? # Optional plus/minus sign (drop this part if you don't want to allow negatives)
(?=.?\d) # Must have at least one numeral (not an empty string or just `.`)
\d* # Optional integer part of any length
(\.\d{0,9}) # Optional decimal part of up to 9 digits
Since both sides of the decimal point are optional, the (?=.?\d) makes sure at least one of them is present. So the number can have an integer part, a decimal part, or both, but not neither.
One thing I want to note is that this pattern allows 23., which was in your example. Personally, I'd call that an invalid number, but it's up to you. If you change your mind on that one, it gets a lot simpler (demo):
/^[+-]?\d*\.?\d{1,9}$/