[regex] Simple regular expression for a decimal with a precision of 2

What is the regular expression for a decimal with a precision of 2?

Valid examples:

123.12
2
56754
92929292929292.12
0.21
3.1

Invalid examples:

12.1232
2.23332
e666.76

The decimal point may be optional, and integers may also be included.

This question is related to regex

The answer is


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

And since regular expressions are horrible to read, much less understand, here is the verbose equivalent:

^                         # Start of string
 [0-9]+                   # Require one or more numbers
       (                  # Begin optional group
        \.                # Point must be escaped or it is treated as "any character"
          [0-9]{1,2}      # One or two numbers
                    )?    # End group--signify that it's optional with "?"
                      $   # End of string

You can replace [0-9] with \d in most regular expression implementations (including PCRE, the most common). I've left it as [0-9] as I think it's easier to read.

Also, here is the simple Python script I used to check it:

import re
deci_num_checker = re.compile(r"""^[0-9]+(\.[0-9]{1,2})?$""")

valid = ["123.12", "2", "56754", "92929292929292.12", "0.21", "3.1"]
invalid = ["12.1232", "2.23332", "e666.76"]

assert len([deci_num_checker.match(x) != None for x in valid]) == len(valid)
assert [deci_num_checker.match(x) == None for x in invalid].count(False) == 0

Won't you need to take the e in e666.76 into account?

With

(e|0-9)\d*\d.\d{1,2)

Chrome 56 is not accepting this kind of patterns (Chrome 56 is accpeting 11.11. an additional .) with type number, use type as text as progress.


 function DecimalNumberValidation() {
        var amounttext = ;
            if (!(/^[-+]?\d*\.?\d*$/.test(document.getElementById('txtRemittanceNumber').value))){
            alert('Please enter only numbers into amount textbox.')
            }
            else
            {
            alert('Right Number');
            }
    }

function will validate any decimal number weather number has decimal places or not, it will say "Right Number" other wise "Please enter only numbers into amount textbox." alert message will come up.

Thanks... :)


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

And since regular expressions are horrible to read, much less understand, here is the verbose equivalent:

^                         # Start of string
 [0-9]+                   # Require one or more numbers
       (                  # Begin optional group
        \.                # Point must be escaped or it is treated as "any character"
          [0-9]{1,2}      # One or two numbers
                    )?    # End group--signify that it's optional with "?"
                      $   # End of string

You can replace [0-9] with \d in most regular expression implementations (including PCRE, the most common). I've left it as [0-9] as I think it's easier to read.

Also, here is the simple Python script I used to check it:

import re
deci_num_checker = re.compile(r"""^[0-9]+(\.[0-9]{1,2})?$""")

valid = ["123.12", "2", "56754", "92929292929292.12", "0.21", "3.1"]
invalid = ["12.1232", "2.23332", "e666.76"]

assert len([deci_num_checker.match(x) != None for x in valid]) == len(valid)
assert [deci_num_checker.match(x) == None for x in invalid].count(False) == 0

This worked with me:

(-?[0-9]+(\.[0-9]+)?)

Group 1 is the your float number and group 2 is the fraction only.


Won't you need to take the e in e666.76 into account?

With

(e|0-9)\d*\d.\d{1,2)

Main answer is WRONG because it valids 5. or 5, inputs

this code handle it (but in my example negative numbers are forbidden):

/^[0-9]+([.,][0-9]{1,2})?$/;

results are bellow:

true => "0" / true => "0.00" / true => "0.0" / true => "0,00" / true => "0,0" / true => "1,2" true => "1.1"/ true => "1" / true => "100" true => "100.00"/ true => "100.0" / true => "1.11" / true => "1,11"/ false => "-5" / false => "-0.00" / true => "101" / false => "0.00.0" / true => "0.000" / true => "000.25" / false => ".25" / true => "100.01" / true => "100.2" / true => "00" / false => "5." / false => "6," / true => "82" / true => "81,3" / true => "7" / true => "7.654"


In general, i.e. unlimited decimal places:

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


Main answer is WRONG because it valids 5. or 5, inputs

this code handle it (but in my example negative numbers are forbidden):

/^[0-9]+([.,][0-9]{1,2})?$/;

results are bellow:

true => "0" / true => "0.00" / true => "0.0" / true => "0,00" / true => "0,0" / true => "1,2" true => "1.1"/ true => "1" / true => "100" true => "100.00"/ true => "100.0" / true => "1.11" / true => "1,11"/ false => "-5" / false => "-0.00" / true => "101" / false => "0.00.0" / true => "0.000" / true => "000.25" / false => ".25" / true => "100.01" / true => "100.2" / true => "00" / false => "5." / false => "6," / true => "82" / true => "81,3" / true => "7" / true => "7.654"


Won't you need to take the e in e666.76 into account?

With

(e|0-9)\d*\d.\d{1,2)

Chrome 56 is not accepting this kind of patterns (Chrome 56 is accpeting 11.11. an additional .) with type number, use type as text as progress.


In general, i.e. unlimited decimal places:

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


adding my answer too, someone might find it useful or may be correct mine too.

function getInteger(int){
  var regx = /^[-+]?[\d.]+$/g;
  return regx.test(int);
}


alert(getInteger('-11.11'));

preg_match("/^-?\d+[\.]?\d\d$/", $sum)

This worked with me:

(-?[0-9]+(\.[0-9]+)?)

Group 1 is the your float number and group 2 is the fraction only.


To include an optional minus sign and to disallow numbers like 015 (which can be mistaken for octal numbers) write:

-?(0|([1-9]\d*))(\.\d+)?

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

Will make things like 12. accepted. This is not what is commonly accepted but if in case you need to be “flexible”, that is one way to go. And of course [0-9] can be replaced with \d, but I guess it’s more readable this way.


I tried one with my project. This allows numbers with + | - signs as well.

/^(\+|-)?[0-9]{0,}((\.){1}[0-9]{1,}){0,1}$/

For numbers that don't have a thousands separator, I like this simple, compact regex:

\d+(\.\d{2})?|\.\d{2}

or, to not be limited to a precision of 2:

\d+(\.\d*)?|\.\d+

The latter matches
1
100
100.
100.74
100.7
0.7
.7
.72

And it doesn't match empty string (like \d*.?\d* would)


I use this one for up to two decimal places:
(^(\+|\-)(0|([1-9][0-9]*))(\.[0-9]{1,2})?$)|(^(0{0,1}|([1-9][0-9]*))(\.[0-9]{1,2})?$) passes:
.25
0.25
10.25
+0.25

doesn't pass:
-.25
01.25
1.
1.256


Won't you need to take the e in e666.76 into account?

With

(e|0-9)\d*\d.\d{1,2)

 function DecimalNumberValidation() {
        var amounttext = ;
            if (!(/^[-+]?\d*\.?\d*$/.test(document.getElementById('txtRemittanceNumber').value))){
            alert('Please enter only numbers into amount textbox.')
            }
            else
            {
            alert('Right Number');
            }
    }

function will validate any decimal number weather number has decimal places or not, it will say "Right Number" other wise "Please enter only numbers into amount textbox." alert message will come up.

Thanks... :)


Try this

 (\\+|-)?([0-9]+(\\.[0-9]+))

It will allow positive and negative signs also.


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

And since regular expressions are horrible to read, much less understand, here is the verbose equivalent:

^                         # Start of string
 [0-9]+                   # Require one or more numbers
       (                  # Begin optional group
        \.                # Point must be escaped or it is treated as "any character"
          [0-9]{1,2}      # One or two numbers
                    )?    # End group--signify that it's optional with "?"
                      $   # End of string

You can replace [0-9] with \d in most regular expression implementations (including PCRE, the most common). I've left it as [0-9] as I think it's easier to read.

Also, here is the simple Python script I used to check it:

import re
deci_num_checker = re.compile(r"""^[0-9]+(\.[0-9]{1,2})?$""")

valid = ["123.12", "2", "56754", "92929292929292.12", "0.21", "3.1"]
invalid = ["12.1232", "2.23332", "e666.76"]

assert len([deci_num_checker.match(x) != None for x in valid]) == len(valid)
assert [deci_num_checker.match(x) == None for x in invalid].count(False) == 0

This will allow decimal with exponentiation and upto 2 digits ,

^[+-]?\d+(\.\d{2}([eE](-[1-9]([0-9]*)?|[+]?\d+))?)?$

Demo


I tried one with my project. This allows numbers with + | - signs as well.

/^(\+|-)?[0-9]{0,}((\.){1}[0-9]{1,}){0,1}$/

preg_match("/^-?\d+[\.]?\d\d$/", $sum)

adding my answer too, someone might find it useful or may be correct mine too.

function getInteger(int){
  var regx = /^[-+]?[\d.]+$/g;
  return regx.test(int);
}


alert(getInteger('-11.11'));

Try this

 (\\+|-)?([0-9]+(\\.[0-9]+))

It will allow positive and negative signs also.


For numbers that don't have a thousands separator, I like this simple, compact regex:

\d+(\.\d{2})?|\.\d{2}

or, to not be limited to a precision of 2:

\d+(\.\d*)?|\.\d+

The latter matches
1
100
100.
100.74
100.7
0.7
.7
.72

And it doesn't match empty string (like \d*.?\d* would)


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

And since regular expressions are horrible to read, much less understand, here is the verbose equivalent:

^                         # Start of string
 [0-9]+                   # Require one or more numbers
       (                  # Begin optional group
        \.                # Point must be escaped or it is treated as "any character"
          [0-9]{1,2}      # One or two numbers
                    )?    # End group--signify that it's optional with "?"
                      $   # End of string

You can replace [0-9] with \d in most regular expression implementations (including PCRE, the most common). I've left it as [0-9] as I think it's easier to read.

Also, here is the simple Python script I used to check it:

import re
deci_num_checker = re.compile(r"""^[0-9]+(\.[0-9]{1,2})?$""")

valid = ["123.12", "2", "56754", "92929292929292.12", "0.21", "3.1"]
invalid = ["12.1232", "2.23332", "e666.76"]

assert len([deci_num_checker.match(x) != None for x in valid]) == len(valid)
assert [deci_num_checker.match(x) == None for x in invalid].count(False) == 0

I use this one for up to two decimal places:
(^(\+|\-)(0|([1-9][0-9]*))(\.[0-9]{1,2})?$)|(^(0{0,1}|([1-9][0-9]*))(\.[0-9]{1,2})?$) passes:
.25
0.25
10.25
+0.25

doesn't pass:
-.25
01.25
1.
1.256


This will allow decimal with exponentiation and upto 2 digits ,

^[+-]?\d+(\.\d{2}([eE](-[1-9]([0-9]*)?|[+]?\d+))?)?$

Demo


To include an optional minus sign and to disallow numbers like 015 (which can be mistaken for octal numbers) write:

-?(0|([1-9]\d*))(\.\d+)?

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

Will make things like 12. accepted. This is not what is commonly accepted but if in case you need to be “flexible”, that is one way to go. And of course [0-9] can be replaced with \d, but I guess it’s more readable this way.