Rich2233
Rich2233

Reputation: 185

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?

Upvotes: 14

Views: 64775

Answers (6)

sultanmb26
sultanmb26

Reputation: 61

I have done one in case people are interested: ^([0-9]*)(.[[0-9]+]?)?$

but it doesn't have '+' sign while also it doesn't accept '-' sign

It accepts:

0
0.5
1.0
1.5
2.0
2.5
3.0
1
2
3
4
0.0
0.1
0.9
0.4
1.3
1.11
1.51
2.01
01.5
0.51
1.1
.1

Reject:

-1.0
-0.5
-0.0
-0.1
-0.7
11123.
1.001.
.1.1

Upvotes: 0

Ashwin Bhamare
Ashwin Bhamare

Reputation: 435

I have found something interesting which work for me!!! hope so for you also...!!!

[0-9].[0-9]

Regex for accepting only a positive number with a decimal point

Matches: 1, 2564, 2.5545, 254.555

Not Matches: -333, 332.332.332, 66-665.455, 55554-4552

Upvotes: 1

Mike Samuel
Mike Samuel

Reputation: 120496

/^[+]?([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]+)?$/

Upvotes: 37

Madhavi Salunke
Madhavi Salunke

Reputation: 21

You can try this -

^\d{0,10}(\.\d{0,2})?$

Also one cool site to test as well as to get description of your own regular expressions https://regex101.com/

Upvotes: 2

Mike Christensen
Mike Christensen

Reputation: 91600

How about like:

^[.]?[0-9]+[.]?[0-9]*$

Upvotes: 1

Daniel Mendel
Daniel Mendel

Reputation: 10003

There are few different ways to do this depending on your need:

/^[0-9.]+$/ matches 1 and 1.1 but not -1

/^[0-9]+\.[0-9]+$/ matches 1.1 but not 1 or -1

Generally, I recommend using a simple regExp reference guide like http://www.regular-expressions.info/ for building expressions, and then test them using javascript right your browser console:

"123.45".match(/^[0-9.]+$/)

Upvotes: 3

Related Questions