Simple regular expression for a decimal with a precision of 2

后端 未结 17 2039
闹比i
闹比i 2020-11-22 02:02

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
相关标签:
17条回答
  • 2020-11-22 02:43

    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'));
    
    0 讨论(0)
  • 2020-11-22 02:44

    This worked with me:

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

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

    0 讨论(0)
  • 2020-11-22 02:45
    ^[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
    
    0 讨论(0)
  • 2020-11-22 02:45

    Try this

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

    It will allow positive and negative signs also.

    0 讨论(0)
  • 2020-11-22 02:48

    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.

    0 讨论(0)
  • 2020-11-22 02:50

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

    /^(\+|-)?[0-9]{0,}((\.){1}[0-9]{1,}){0,1}$/
    
    0 讨论(0)
提交回复
热议问题