Checking negative and positive decimal numbers with RegEx

I am trying to create a regular expression that will allow both negative and positive decimal numbers with the following rules.

  • after the decimal point there can be no more than two digits
  • Decimal point optional
  • Total length, including decimal point, must not exceed 12 char
  • if there is no decimal point, the maximum length must not exceed 9 char

Can anyone help me out? Thanks a lot in advance.

+5
source share
5 answers

Check out this regex.

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

In this regex

  • Sign
  • is optional
  • at least one and a maximum of 9 digits as an integer part
  • if there is a decimal point, at least one and two two digits after it.
+14
source

This is pretty simple, since 12 - 9 == 3 for two decimal places + a dot.

 var re = new RegExp('^-?\\d{1,9}(\\.\\d{1,2})?$'); 

authorizes

  • -123456789
  • -123456789.1
  • -123456789.12
  • 0
  • 0.12

but will not accept

  • 01234567890123 more than 12 divisions
  • 123. period without decimal places
  • 123.123 more than two decimal places
  • . or .12 (missing 0)
+3
source

My own regex:

 var rgx = /^(-{1}?(?:([0-9]{0,10}))|([0-9]{1})?(?:([0-9]{0,9})))?(?:\.([0-9]{0,3}))?$/; 
+1
source
 var NumberToValidate = 48428; var valid = /^([0-9]*[1-9][0-9]*)$/.test(NumberToValidate); { if (!valid) alert("Invalid Quantity!!\nThe Quantity cannot be Zero\n or a part of a Unit !"); return false; } 
0
source

enter image description here

 /(?:^(?:(?:[1-9][0-9]{1,})|0)\.[0-9]{1,}$)|^[1-9]+[0-9]*$/ 
-1
source

Source: https://habr.com/ru/post/1479903/


All Articles