Mark13426
Mark13426

Reputation: 2639

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

Upvotes: 0

Views: 2590

Answers (3)

hwnd
hwnd

Reputation: 70722

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

Upvotes: 3

mwilson
mwilson

Reputation: 12900

Try this:

var pattern = /^\d+\.0{3,}$/; // Regex from @hwnd

function checkDigits(digits) {

    var result = pattern.test(digits);

    return result;
}

alert(checkDigits("5.000")); //Returns true.

Upvotes: 0

nisargjhaveri
nisargjhaveri

Reputation: 1509

Here is the regex which matches to a . and then 3 or more 0s at the end of the string.

/\.0{3,}$/

Upvotes: 0

Related Questions