Regular Expression to Accept Only Positive Numbers and Decimals

Regular Expression to accept only positive numbers and decimals

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

Regular Expression to accept only positive number and decimals (only end with .5 .0 or integer accepted)

You can check this here at regex101. The regex I used to do this is:

(^0\.5$)|(^[1-9][0-9]*(\.[05])?$)

What is highlighted in blue is a match.

Regular expression for positive decimal number with 0, 1 or 2 decimal places

Edit 2: now disallows exactly 0,0.0, etc.

This matches at least one digit before the decimal place, followed by an optional decimal place, followed by 0-2 digits.

The negative lookahead looks for any flavor of absolute zero and prevents a match.

^(?!0*[.,]0*$|[.,]0*$|0*$)\d+[,.]?\d{0,2}$

This is the raw regex, so you'll need to escape it appropriately for your language. (For example, in some languages you need to double the \ slashes as \\.

/^(?!0*[.,]0*$|[.,]0*$|0*$)\d+[,.]?\d{0,2}$/

RegEx that matches positive numbers

This would be my way: ^[+]?\d+([.]\d+)?$

EDIT: If you want to allow something like .23, you could use ^[+]?([.]\d+|\d+([.]\d+)?)$

EDIT: tchrist insists on this one: allowing 4., you could use ^[+]?([.]\d+|\d+[.]?\d*)$

Explanation:

  • with or without positive sign
  • one or more digits
  • with or without:
    • decimal point
    • one or more digits

Note: This will not accept a negative number, which is what you ultimately want.

Regex for only positive decimals from 0 to 1 upto 2 decimal digits only that works without sign in JavaScript?

You may use:

^(?:0(?:\.[0-9]{1,2})?|1(?:\.00?)?)$

RegEx Demo

RegEx Details:

  • ^: Start
  • (?:: Start a non-capture group
    • 0: Match 0
    • (?:\.[0-9]{1,2})?: Match optional dot followed by 1 or 2 digits
    • |: OR
    • 1: Match 1
    • (?:\.00?)?: Match optional 1 or 2 zeroes after dot
  • ): End non-capture group
  • $: End


Related Topics



Leave a reply



Submit