J. Doe
J. Doe

Reputation: 33

Regext help for decimal numbers

I have regex which should check if string is decimal number...

^([\+\-])?\d{1,10}[\.,]?\d{1,10}?$
  1. start with single + or - //not mandatory
  2. follow with digit
  3. follow with decimal single separator //not mandatory
  4. and follow with one to ten digits //not mandatory -- this should be follow only in case of decimal separator

but is not working in case of

-1 //single digit

and if there are more than 10 digits w/o decimal separator -> should fail

  assertEquals(false,  Util.isDecimalNumber("12345678901"));

Is there a easier way to check if string is a decimal number?

Upvotes: 1

Views: 77

Answers (3)

hjpotter92
hjpotter92

Reputation: 80639

Try the following pattern:

^[-+]?\d{1,10}(?:[.,]\d{1,10})?$

Upvotes: 0

Ahsan
Ahsan

Reputation: 1084

^[\+\-]?\d{1,10}([\.,]\d{1,10})?$

Fiddle: https://regex101.com/r/qQ2dE4/80

Upvotes: 0

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34199

You have an incorrect syntax in the fractional part of your RegExp.

Instead of

^([\+\-])?\d{1,10}[\.,]?\d{1,10}?$

It should be either

^([\+\-])?\d{1,10}([\.,]\d{1,10})?$ 

or

^([\+\-])?\d{1,10}[\.,]?\d{0,10}$

The first one is more suitable, because it disallows decimal point without fractional part like 123..

In words, it will become:

  1. start with single + or - //not mandatory.

  2. follow with digit

  3. follow with decimal single separator and follow with the one to ten digits //not mandatory

Check this Regex101 demo out.

Upvotes: 1

Related Questions