293

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.

Peter O.
  • 28,965
  • 14
  • 72
  • 87
user39221
  • 2,941
  • 2
  • 15
  • 5
  • 1
    Related: for decimal with thousandth separator, see http://stackoverflow.com/questions/16148034/regex-for-number-with-decimals-and-thousand-separator – Yeo Jul 20 '16 at 00:13
  • 2
    The best answer is here: https://stackoverflow.com/a/39399503/715269 – Gangnus Jul 28 '17 at 13:02

17 Answers17

430

Valid regex tokens vary by implementation. A generic form is:

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

More compact:

\d+(\.\d{1,2})?

Both assume that both have at least one digit before and one after the decimal place.

To require that the whole string is a number of this form, wrap the expression in start and end tags such as (in Perl's form):

^\d+(\.\d{1,2})?$

To match numbers without a leading digit before the decimal (.12) and whole numbers having a trailing period (12.) while excluding input of a single period (.), try the following:

^(\d+(\.\d{0,2})?|\.?\d{1,2})$

Added

Wrapped the fractional portion in ()? to make it optional. Be aware that this excludes forms such as 12. Including that would be more like ^\d+\\.?\d{0,2}$.

Added

Use ^\d{1,6}(\.\d{1,2})?$ to stop repetition and give a restriction to whole part of the decimal value.

Dave Jarvis
  • 28,853
  • 37
  • 164
  • 291
DocMax
  • 11,688
  • 7
  • 39
  • 41
  • 5
    Mathematically, I think a precision 2 number should always have two decimals even if the last is zero. This is based on my experience with significant figures so it could be wrong, but you don't actually know if 1.7 is 1.70 or any number from 1.70 to 1.74. – paxdiablo Nov 21 '08 at 09:17
  • Thanks! Was exactly what I needed :) +1 – alex Aug 27 '09 at 00:09
  • 1
    @DocMax, what i need to change if ^\d+(\.\d{1,2})?$ expression to support negative numbers ? like -4509.45 or -.45 or -0.45 – Murali Murugesan Feb 06 '13 at 09:55
  • 3
    Added '-?' in this ^\d+(\.\d{1,2})?$ ===> ^-?\d+(\.\d{1,2})?$ for supporting -ve – Murali Murugesan Feb 06 '13 at 10:00
  • To accept something like .21 or .99 use this (^[0-9]+(\.[0-9]{1,2})?$)|(^(\.[0-9]{1,2})?$) – Raymund Aug 08 '13 at 02:45
  • To validate decimals using prototype chkout [this link](http://stackoverflow.com/questions/4572194/regex-to-replace-everything-except-numbers-and-a-decimal-point) – Parik Tiwari Oct 29 '13 at 00:47
  • For also supporting .21 you could use this ^([0-9]+)?(\\.)?([0-9]{1,2})?$ – Zeb-ur-Rehman Feb 06 '15 at 04:58
  • how to allow only 12 digit before decimal – albert Jegani Feb 16 '16 at 13:09
  • @albertJegani, If you want exactly 12 digits start with `^\d{12}`, but if you want any number up to 12, `^\d{1,12}` – DocMax Feb 16 '16 at 18:21
  • @albertJegani, you have a stray `+`. Try `^\d{1,12}(\.\d{1,2})?$` to allow 1-12 digits followed by an optional period and up to two more digits. – DocMax Feb 17 '16 at 17:17
  • This is not working in chrome 56, 11.11. two dots are being accepted strangely. – rajesh_kw Feb 08 '17 at 11:30
  • 1
    @BimalDas, you can support negatives by prefixing the expression with `-?` , as in `-?\d+(\.\d{1,2})?`. I did not include negatives or starting with a decimal point as those were not in the OP's question, although they are certainly valid for a more generic number format. The comments thread here gives a few ways to handle ".21". – DocMax Jul 21 '17 at 16:06
  • how can I accept what you did with decimal separated by , and also by . ? – Mago Nicolas Palacios May 25 '20 at 17:27
294
^[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
isherwood
  • 46,000
  • 15
  • 100
  • 132
dbr
  • 153,498
  • 65
  • 266
  • 333
  • I want max 3 digits before decimal, tried like this with no luck ^([0-9]{0,3})+(\.[0-9]{1,2})?$ – Raghurocks Oct 15 '13 at 06:17
  • 3
    @Raghurocks Remove the `+` after the first closing paren, `^([0-9]{0,3})(\.[0-9]{1,2})?$` – dbr Oct 17 '13 at 12:55
  • For Java users: the decimal shouldn't be escaped. –  Jan 26 '14 at 22:10
  • 3
    @Gracchus Are you sure? It should probably be `\\.` instead of `\.` because `.` will look like it works, but matches any character (not just the decimal place). For example, both `1z23` and `1.23` might be considered valid if you don't escape it – dbr Jan 27 '14 at 02:27
  • @dbr Maybe that's what it should be. Java just complained about improper escaping. Removing that "fixed it" (shut it up), lol. I haven't had a chance to fully test it just yet. –  Jan 27 '14 at 02:31
  • You might also want to use the decimal separator as defined in the current Locale, rather than putting it in the regex explicitly? – Paul Eden Mar 20 '14 at 16:01
  • @PaulEden maybe, depends what you are parsing - if it's human-typed input, sure; if you are parsing a file containing `1.23` format numbers, definitely not – dbr Mar 21 '14 at 10:24
  • Wish I had a little reference guide of these line-by-line regex diagrams. – PJ Brunet Aug 29 '20 at 18:35
19

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+)?
bluish
  • 23,093
  • 23
  • 110
  • 171
14

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)

Jimmy
  • 4,610
  • 8
  • 51
  • 71
8
^[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.

tchrist
  • 74,913
  • 28
  • 118
  • 169
BSharper
  • 81
  • 1
  • 1
8

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

5

Try this

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

It will allow positive and negative signs also.

bluish
  • 23,093
  • 23
  • 110
  • 171
Android
  • 8,412
  • 9
  • 64
  • 107
2

In general, i.e. unlimited decimal places:

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

SK9
  • 29,437
  • 32
  • 112
  • 154
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"

Vivien Pipo
  • 3,876
  • 5
  • 21
  • 52
2
preg_match("/^-?\d+[\.]?\d\d$/", $sum)
DEC32
  • 21
  • 1
1

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'));
STEEL
  • 5,589
  • 8
  • 52
  • 73
1

This worked with me:

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

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

Shady Mohamed Sherif
  • 12,005
  • 4
  • 34
  • 45
1

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

With

(e|0-9)\d*\d.\d{1,2)
bluish
  • 23,093
  • 23
  • 110
  • 171
spacemonkeys
  • 1,559
  • 5
  • 15
  • 28
1

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

/^(\+|-)?[0-9]{0,}((\.){1}[0-9]{1,}){0,1}$/
Rino Raj
  • 6,041
  • 2
  • 22
  • 37
Premanshu
  • 606
  • 2
  • 13
  • 22
0

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.

rajesh_kw
  • 1,446
  • 16
  • 14
0

This will allow decimal with exponentiation and upto 2 digits ,

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

Demo

Nambi_0915
  • 961
  • 4
  • 21
-1
 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... :)

Bhanu Pratap
  • 1,225
  • 12
  • 14