Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex - check for decimal(javascript)

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?

like image 896
CocaCola Avatar asked Jun 08 '11 20:06

CocaCola


People also ask

How to check valid decimal value in JavaScript?

To validate decimal numbers in JavaScript, use the match() method. It retrieves the matches when matching a string against a regular expression.

How do you validate decimal numbers?

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.


2 Answers

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+)$/ );
like image 112
Ben Roux Avatar answered Sep 27 '22 18:09

Ben Roux


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}$/
like image 30
Justin Morgan Avatar answered Sep 27 '22 18:09

Justin Morgan