RegEx needed to match number to exactly two decimal places

后端 未结 5 1377
醉梦人生
醉梦人生 2020-12-06 09:48

I need some regex that will match only numbers that are decimal to two places. For example:

  • 123 = No match
  • 12.123 = No match
  • 12.34 = Match
相关标签:
5条回答
  • 2020-12-06 10:26
    ^[0-9]*\.[0-9]{2}$ or ^[0-9]*\.[0-9][0-9]$
    
    0 讨论(0)
  • 2020-12-06 10:26
    var regexp = /^[0-9]*(\.[0-9]{0,2})?$/;
    
    //returns true
    regexp.test('10.50')
    
    //returns false
    regexp.test('-120')
    
    //returns true
    regexp.test('120.35')
    
    //returns true
    regexp.test('120')
    
    0 讨论(0)
  • 2020-12-06 10:37

    It depends a bit on what shouldn't match and what should and in what context

    for example should the text you test against only hold the number? in that case you could do this:

    /^[0-9]+\.[0-9]{2}$/
    

    but that will test the entire string and thus fail if the match should be done as part of a greater whole

    if it needs to be inside a longer styring you could do

    /[0-9]+\.[0-9]{2}[^0-9]/
    

    but that will fail if the string is is only the number (since it will require a none-digit to follow the number)

    if you need to be able to cover both cases you could use the following:

    /^[0-9]+\.[0-9]{2}$|[0-9]+\.[0-9]{2}[^0-9]/
    
    0 讨论(0)
  • 2020-12-06 10:40

    If you're looking for an entire line match I'd go with Paul's answer.

    If you're looking to match a number witihn a line try: \d+\.\d\d(?!\d)

    • \d+ One of more digits (same as [0-9])
    • \. Matches to period character
    • \d\d Matches the two decimal places
    • (?!\d) Is a negative lookahead that ensure the next character is not a digit.
    0 讨论(0)
  • 2020-12-06 10:45

    You can also try Regular Expression

    ^\d+(\.\d{1,2})?$
    
    or
    var regexp = /^\d+\.\d{0,2}$/;
    
    // returns true
    regexp.test('10.5')
    
    or
    [0-9]{2}.[0-9]{2}
    
    or
    ^[0-9]\d{0,9}(\.\d{1,3})?%?$
    
    or
    ^\d{1,3}(\.\d{0,2})?$
    
    0 讨论(0)
提交回复
热议问题