Regular expression for 6 digit number with optional 2 decimal digits

Swapnil picture Swapnil · Jan 28, 2013 · Viewed 36.2k times · Source

I need a regular expression for 6 digit number with optional 2 decimal digit Allowed values:

    .1  .11  0.11  10. 10.1   10.12  00.00  0.0  00.00

   123456 12345 1234 123 12 1 0 0. 123. 123.55 123456.  

Answer

Hui Zheng picture Hui Zheng · Jan 28, 2013

Regex should be: ^\d{0,6}(\.\d{0,2})?$(It passed all of your samples)

Update:

To avoid empty string and single dot, regex is ^(?!\.?$)\d{0,6}(\.\d{0,2})?$. The expression adds a negative lookahead ?!\.?$, which excludes 0 or 1 dot.

I added a unit test on Fiddle.