I need a regular expression in javascript that will accept only positive numbers and decimals. This is what I have but something is wrong -- it doesn't seem to take single positive digits.
/^[-]?[0-9]+[\.]?[0-9]+$/;
For example, 9
will not work. How can I restructure this so if there is at least one positive digit, it will work?
To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.
Positive decimal first and foremost is a value that is positive. That is, it is greater than 0. In the same way that a negative number is less than 0. Some people tend to consider the only decimal part of 2751.89105 to be the .
positive numbers are numbers which are greater than zero. Product of two positive rational numbers is always positive.
/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/
matches
0
+0
1.
1.5
.5
but not
.
1..5
1.2.3
-1
EDIT:
To handle scientific notation (1e6
), you might want to do
/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/
If you want strictly positive numbers, no zero, you can do
/^[+]?([1-9][0-9]*(?:[\.][0-9]*)?|0*\.0*[1-9][0-9]*)(?:[eE][+-][0-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