Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate negative and positive decimal numbers with RegEx

I am trying to build a regex which will allow both negative and positive decimal numbers with the following rules.

  1. there can not be more than 2 digits after decimal point
  2. Decimal point is optional
  3. Total length including decimal point should not exceed 12 char
  4. if no decimal point is there, max length should not exceed 9 char

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

like image 778
Manas Saha Avatar asked May 09 '13 11:05

Manas Saha


People also ask

Can regex tester check for negative or positive numbers?

A number, which is a negative or positive dot-separated decimal, or a negative or positive integer. Suitable to check for input of numerical values. Regex Tester isn't optimized for mobile devices yet. You can still take a look, but it might be a bit quirky. > Okay! Regex Tester requires a modern browser.

How do you write a regular expression for a decimal number?

A regular expression for a decimal number needs to checks for one or more numeric characters (0-9) at the start of the string, followed by an optional period, and then followed by zero or more numeric characters (0-9). This should all be followed by an optional plus or minus sign.

How to match only decimal numbers with nothing behind it?

And finally, to ensure that this regex matches only a decimal number with nothing in front and nothing behind it, we can add the start-of-string (^) and end-of-string ($) characters to the start and end, respectively:

What is the best way to use regex with numbers?

Use number input is the best way for your problem. But if you really want use regex you can use one of two regex above.


1 Answers

Check this regex.

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

This regex says

  • sign is optional
  • at least one and max 9 digits as integer part
  • if decimal point is there, at least one and max two digits after it.
like image 78
Bilal Mirza Avatar answered Nov 12 '22 06:11

Bilal Mirza