Simple regular expression for a decimal with a precision of 2
Asked Answered
M

19

295

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.

Miriam answered 21/11, 2008 at 7:29 Comment(2)
Related: for decimal with thousandth separator, see #16148534Conan
The best answer is here: https://mcmap.net/q/102024/-decimal-or-numeric-values-in-regular-expression-validationUniverse
P
435

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.

Potluck answered 21/11, 2008 at 7:32 Comment(12)
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.Laaland
@DocMax, what i need to change if ^\d+(\.\d{1,2})?$ expression to support negative numbers ? like -4509.45 or -.45 or -0.45Kp
Added '-?' in this ^\d+(\.\d{1,2})?$ ===> ^-?\d+(\.\d{1,2})?$ for supporting -veKp
To accept something like .21 or .99 use this (^[0-9]+(\.[0-9]{1,2})?$)|(^(\.[0-9]{1,2})?$)Ladida
To validate decimals using prototype chkout this linkBerkshire
For also supporting .21 you could use this ^([0-9]+)?(\\.)?([0-9]{1,2})?$Preconcert
how to allow only 12 digit before decimalFranek
@albertJegani, If you want exactly 12 digits start with ^\d{12}, but if you want any number up to 12, ^\d{1,12}Potluck
@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.Potluck
This is not working in chrome 56, 11.11. two dots are being accepted strangely.Carmellacarmelle
@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".Potluck
how can I accept what you did with decimal separated by , and also by . ?Football
V
301
^[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
Vaticinal answered 21/11, 2008 at 8:49 Comment(8)
I want max 3 digits before decimal, tried like this with no luck ^([0-9]{0,3})+(\.[0-9]{1,2})?$Debrief
@Debrief Remove the + after the first closing paren, ^([0-9]{0,3})(\.[0-9]{1,2})?$Vaticinal
For Java users: the decimal shouldn't be escaped.Ordinate
@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 itVaticinal
@Vaticinal 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.Ordinate
You might also want to use the decimal separator as defined in the current Locale, rather than putting it in the regex explicitly?Cormorant
@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 notVaticinal
Wish I had a little reference guide of these line-by-line regex diagrams.Kulseth
I
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+)?
Inspirit answered 18/6, 2010 at 9:32 Comment(2)
This is allowing alpha before the decimal for me. Allows X.25Mosier
This doesn't limit the number of decimal places to 2.Pensionary
P
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)

Proposal answered 19/1, 2012 at 2:55 Comment(0)
H
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

Hardboiled answered 26/8, 2011 at 15:55 Comment(1)
This also passes a blank value.Mosier
D
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.

Deadly answered 8/9, 2012 at 0:56 Comment(1)
Working Fine. Thanks :)Kat
E
5

Try this

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

It will allow positive and negative signs also.

Elvinaelvira answered 14/6, 2011 at 5:4 Comment(0)
S
2
preg_match("/^-?\d+[\.]?\d\d$/", $sum)
Squalid answered 13/7, 2011 at 10:51 Comment(0)
L
2

In general, i.e. unlimited decimal places:

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

Lesterlesya answered 8/6, 2012 at 3:14 Comment(1)
Doesn't match 22.00, for exampleUnkempt
L
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"

Level answered 5/4, 2018 at 8:50 Comment(0)
I
1

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

With

(e|0-9)\d*\d.\d{1,2)
Irade answered 21/11, 2008 at 7:36 Comment(1)
No, That would be out of the scope of the project! thanks though, it is handy:)Miriam
H
1

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

/^(\+|-)?[0-9]{0,}((\.){1}[0-9]{1,}){0,1}$/
Hoffarth answered 3/11, 2011 at 5:38 Comment(0)
W
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'));
Weldon answered 23/5, 2014 at 9:13 Comment(0)
D
1

This worked with me:

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

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

Dangelo answered 23/3, 2015 at 15:8 Comment(0)
C
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.

Carmellacarmelle answered 8/2, 2017 at 12:1 Comment(0)
B
0

This will allow decimal with exponentiation and upto 2 digits ,

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

Demo

Barong answered 4/9, 2018 at 10:3 Comment(3)
That doesn't match integer nor 1.2e-10Cusco
Yeah, thank you for your correction. I thought its only for decimal numbersBarong
([0-9]+)? is better written \d*. Now it doesn't match 10e3. And OP wants to match upto 2 digits.Cusco
A
0

Use the following regular expression to support negative numbers like -4509.45

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

DEMO.

Alow answered 26/1 at 19:26 Comment(0)
S
0

There are also few other example where we need to handle it more properly.

For Ex.

  1. 123.100000 -> True (123.1 and 123.100000 both are same value)
  2. 123.110000 -> True (123.11 and 123.110000 both are same value)
  3. 123.11001 -> False (123.1101 contains last decimal point with positive value so it is false)

Here is the regex you can use to achieve all cases from you question and also from above examples

/^\d+(\.\d{1,2}0*)?$/
  • ^: asserts the start of the string.
  • \d+: matches one or more digits.
  • (.\d{1,2}0*)?: This is an optional group for the decimal part.
  • .: matches the decimal point.
  • \d{1,2}: matches one or two digits after the decimal point.
  • 0*: matches zero or more zeros after the decimal digits.
  • $: asserts the end of the string.
Solano answered 31/1 at 7:41 Comment(0)
S
-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... :)

Stepdame answered 6/9, 2016 at 18:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.