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?
To validate decimal numbers in JavaScript, use the match() method. It retrieves the matches when matching a string against a regular expression.
It is compulsory to have a dot ('. ') in a text for a decimal value. Minus is used as a decimal number and can be a signed number also. Sign decimal numbers, like -2.3, -0.3 can have minus sign at first position only.
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+)$/ );
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}$/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With