Regex - check decimal (javascript)

I got this expression from stackoverflow itself - /^\d+(\.\d{0,9})?$/ .

Take care:

 2 23 23. 25.3 25.4334 0.44 

but does not work on .23 . Could this be added to the above expression or something that takes care of all of them?

+7
source share
3 answers

This will capture every case you posted as well .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+)$/ ); 
+24
source

This covers all of your examples, allows for negatives, and applies a 9-digit decimal limit:

 /^[+-]?(?=.?\d)\d*(\.\d{0,9})?$/ 

Demo Version: https://regexr.com/4chtk

To break this:

 [+-]? # 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, (?=.?\d) ensures that at least one of them is present. Thus, a number can have an integer part, a decimal part, or both, but not both.

One thing that I want to point out is that this template allows 23. , which was in your example. Personally, I would call it the wrong number, but it's up to you. If you change your mind about this, it will become much easier ( demo ):

 /^[+-]?\d*\.?\d{1,9}$/ 
+2
source

Try the following expression:

^\d*\.?\d*$

+1
source

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


All Articles