Swapnil
Swapnil

Reputation: 26

regular expression for number with decimal places

Can anyone help me build javscript regular expression to validate 6 digit number with 2 deimal places? These examples should pass the test

0,  0.0,  0.33,  1, 11,  111, 1111, 11111,  111111
1.33, 1.3, 12.33, 12.3, 123.0, 123.33, 1234.0, 1234.11

tried this:

/^\d{1,4}(\.\d{1,2})?$/ 

but it fails in jquery when .(dot) is pressed

Upvotes: 0

Views: 5726

Answers (3)

Hui Zheng
Hui Zheng

Reputation: 10224

Try regex: /^\d{1,6}(\.\d{1,2})?$/. Note: you need escape dot.

If what you require is the total number of digits(including those after decimal point) is at most 6, then regex will be: /^(?!.{8,})\d{1,6}(\.\d{1,2})?$/. The expression adds a negative lookahead ?!.{8,}, which will exclude those digits having length larger than 7.

Update: As @Christoph pointed out, "01.23" should be excluded, then the above two expressions should be /^([1-9]\d{0,5}|0)(\.\d{1,2})?$/ and /^(?!.{8,})([1-9]\d{0,5}|0)(\.\d{1,2})?$/ respectively.

Upvotes: 3

Mike T
Mike T

Reputation: 4787

DOT is a special character and needs to be escaped. You should use "\."

The easiest would be to first check that the length of the String is less than 7 (6 digits and 1 dot) using an appropriate jquery function. That deals with the length.

Then for the regex, you just need to check that it has at most 2 decimal places which you could do with this: /^\d{1,6}(\.\d{1,2})?$/

http://www.regular-expressions.info/dot.html

Upvotes: 0

pstr
pstr

Reputation: 384

When you press dot there are no digits after it yet and your regexp fails. So you can try this regexp /^\d{1,6}(\.\d{0,2})?$/ to allow this situation, but be aware that user would be able to enter numbers like this 12345.

Upvotes: 1

Related Questions