Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to accept only positive numbers and decimals

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?

like image 935
Rich2233 Avatar asked Oct 10 '11 03:10

Rich2233


People also ask

How do you use numbers in regular expressions?

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.

What is a positive decimal number?

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 .

Which are positive numbers?

positive numbers are numbers which are greater than zero. Product of two positive rational numbers is always positive.


1 Answers

/^[+]?([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]+)?$/
like image 125
Mike Samuel Avatar answered Sep 29 '22 09:09

Mike Samuel