Regex take only 2 places after

Hello everyone. I need all of these possible cases to be valid.

123 123.1 123.12 

I tried this ^[0-9]*\.[0-9]{2}$ or ^[0-9]*\.[0-9][0-9]$ , but it doesn’t work, maybe someone help me sometime.

+7
source share
5 answers

Try the following:

 ^[0-9]*(\.[0-9]{1,2})?$ 

According to your second example, but allows one or two decimal places, and makes the full decimal part optional.

[EDIT]

The OP changed the question criteria - see comments below. Now he wants the digits to the decimal point to allow up to six digits and asked me to edit the answer.

All that is needed is to replace * (for any number of digits) with {0,6} (between zero and six digits). If you need at least one digit, then it will be {1,6} .

Here is a modified regex:

 ^[0-9]{0,6}(\.[0-9]{1,2})?$ 
+12
source

try ...

 ^\d{1,6}(?:\.\d{1,2})?$ 

* Edited as suggested to make it non-exciting.

+5
source

almost got it ...

^[0-9]*(\.[0-9]{1,2})?$

+1
source

You may also need to worry about numbers starting with a dot, treat the dot without any numbers as invalid, and reject empty numbers:

 ^(?:\d+|\d*\.\d{1,2})$ 

This accepts 1 , .1 , 1.0 , but rejects . , 1. and (empty number).

+1
source

Try this according to all your requirements.

  ^(\d{0,6})(\.\d{1,2})?$ 
+1
source

All Articles