Search code examples
javascriptregexdecimal-point

Javascript regex involving zeros after the decimal point


What would be the javascript regex to determine whether the digits after the decimal point are only zero and the number of zeros after the decimal point is greater than two?

Some test cases:

8 -> false
8.0 -> false
8.00 -> false
8.000 -> true
8.0000 -> true
8.00001 -> false

Solution

  • Based off your comments, if 0.000 is legal and you want to reject mutliple leading zeros along with only zeros after the decimal point being greater than two, the following should work for you.

    /^(?!00)\d+\.0{3,}$/
    

    Explanation:

    ^         # the beginning of the string
    (?!       # look ahead to see if there is not:
      00      #   '00'
    )         # end of look-ahead
     \d+      #   digits (0-9) (1 or more times)
     \.       #   '.'
     0{3,}    #   '0' (at least 3 times)
    $         # before an optional \n, and the end of the string
    

    Live Demo