Decimal number regular expression, where digit after decimal is optional
I need a regular expression that validates a number, but doesn't require a digit after the decimal. ie.
123
123.
123.4
would all be valid
123..
would be invalid
Any would be greatly appreciated!
Use the following:
/^\d*\.?\d*$/
-
^
- Beginning of the line; -
\d*
- 0 or more digits; -
\.?
- An optional dot (escaped, because in regex,.
is a special character); -
\d*
- 0 or more digits (the decimal part); -
$
- End of the line.
This allows for .5 decimal rather than requiring the leading zero, such as 0.5
/\d+\.?\d*/
One or more digits (\d+
), optional period (\.?
), zero or more digits (\d*
).
Depending on your usage or regex engine you may need to add start/end line anchors:
/^\d+\.?\d*$/
Debuggex Demo
You need a regular expression like the following to do it properly:
/^[+-]?((\d+(\.\d*)?)|(\.\d+))$/
The same expression with whitespace, using the extended modifier (as supported by Perl):
/^ [+-]? ( (\d+ (\.\d*)?) | (\.\d+) ) $/x
or with comments:
/^ # Beginning of string
[+-]? # Optional plus or minus character
( # Followed by either:
( # Start of first option
\d+ # One or more digits
(\.\d*)? # Optionally followed by: one decimal point and zero or more digits
) # End of first option
| # or
(\.\d+) # One decimal point followed by one or more digits
) # End of grouping of the OR options
$ # End of string (i.e. no extra characters remaining)
/x # Extended modifier (allows whitespace & comments in regular expression)
For example, it will match:
- 123
- 23.45
- 34.
- .45
- -123
- -273.15
- -42.
- -.45
- +516
- +9.8
- +2.
- +.5
And will reject these non-numbers:
- . (single decimal point)
- -. (negative decimal point)
- +. (plus decimal point)
- (empty string)
The simpler solutions can incorrectly reject valid numbers or match these non-numbers.
this matches all requirements:
^\d+(\.\d+)?$
Try this regex:
\d+\.?\d*
\d+ digits before optional decimal
.? optional decimal(optional due to the ? quantifier)
\d* optional digits after decimal