0

how to validate numbers between 0 to 99999.99 using regex?

basically it should accept the values like 0.01, 0000.01, .01 and 9999.99

also it should have only two values after dot(.)

I tried something like the below but it did not work for me.

/^[0-9]{1,5}.[0-9]{2}$/ 

decimal is optional

Could someone help pls.

1
  • Is this javascript or java, and what does "it did not work for me" mean? Commented Mar 16, 2016 at 4:42

4 Answers 4

3

The . character has special meaning in a regex, so you need to escape it.

Anyway, let me see if I got the rules straight:

  • Decimal point is optional
  • If decimal point not given:
    • Between 1 and 5 digits
  • If decimal point is present:
    • Between 0 and 5 digits before decimal point
    • Between 1 and 2 digits after decimal point

Since the number of digits depends on the presence of the decimal point, you make the regex have two choices, separated by |.

Choice 1 (no decimal point): [0-9]{1,5}

Choice 2 (decimal point): [0-9]{0,5}\.[0-9]{1,2}

Since you want anchors (^$), you can either put them in both choices, or surround the choice set with parenthesis. To make it non-capturing, use (?:xxx).

Final regex is one of these:

/^[0-9]{1,5}$|^[0-9]{0,5}\.[0-9]{1,2}$/
/^(?:[0-9]{1,5}|[0-9]{0,5}\.[0-9]{1,2})$/

You can see the second one in effect on regex101.

Sign up to request clarification or add additional context in comments.

Comments

0

If javascript then below regex would work:

^\d{0,5}(((\.){0})|((\.){1}\d{1,2}))$

All the above mentioned cases are satisfying.

Comments

0

Javascript regex:

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

Javascript demo

Comments

0

The regex ^(?:\d{1,5}(?:\.\d{1,2})?|\.\d{1,2})$ is what I was trying to get.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.