Srini V
Srini V

Reputation: 11375

Regex to validate decimals

I need to validate the integers with the below pattern. Integer part can have up to 5 characters and the fraction value can have up to 2 chars. (fraction value is optional). Leading + or - is also optional.

(+/-) mmmmm (5).nn (2)

Test data

Valid
-1
+1
1
+.1
-.1
.1
+11111.11
-11111.11
11111

Invalid
+111111.11
-111111.11
+11111.111
-11111.111
11111.111
111111.11
+1.
-1.
1. 

This is what I currently use

[+-]?\d{0,5}\.?\d{1,2}?

Is this correct? Am I missing something obvious?

Here is the test case.

EDIT

If there is an additional constraint to have the number of digits from the scale is included in the precision.

For example DECIMAL(5, 2) defines numbers of the form 1234.5 whereas DECIMAL(5, 5) defines numbers of the form 1.2345. How should I change this?

Upvotes: 3

Views: 87

Answers (3)

rishat
rishat

Reputation: 8376

In Javascript, you can validate a number using

Number(n) === Number(n)

For any non-number values of n, like "abc" or [1, 2, 3], Number(n) will return NaN. Given that NaN !== NaN in any case, you can easily tell if n is a number.

Number constructor works fine with almost any form of number representation:

Number(123) // -> 123
Number('123') // -> 123
Number('+12e+3') // -> 12000
Number('-1.2e-3') // -> -0.0012
Number('--123') // -> NaN

However, if you are constrained to using regular expressions, it's very close to what you described:

  1. Optional "+" or "-".
  2. 0 to 5 digits.
  3. Optional "." and then 1 to 2 digits in decimal part. The whole part is optional, meaning that a single dot with no digits is invalid

And no exponential form.

That would be

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

so that

/^[+-]?\d{0,5}(\.\d{1,2})?$/.test(123) // -> true
/^[+-]?\d{0,5}(\.\d{1,2})?$/.test('123') // -> true
/^[+-]?\d{0,5}(\.\d{1,2})?$/.test('+123.45') // -> true
/^[+-]?\d{0,5}(\.\d{1,2})?$/.test('--123') // -> false
/^[+-]?\d{0,5}(\.\d{1,2})?$/.test('-123.456') // -> false

Please note that the part (\.\d{1,2})? is whole optional. In your case, either dot or two decimal digits are optional, so "123." would be a valid number. In Javascript, it is valid, though, so there shouldn't be any problem with that.

Upvotes: 2

dnit13
dnit13

Reputation: 2496

A slight modification in your regex works :

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

or

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

Demo1

Demo2

Upvotes: 1

heemayl
heemayl

Reputation: 42137

Do:

^[+-]?(?:[0-9]{1,5})?(?:\.[0-9]{1,2})?$
  • ^[+-]? matches + or - at start, optional
  • (?:[0-9]{1,5})? matches one to five digits, optional
  • (?:\.[0-9]{1,2})?$ matches a literal dot, followed by one or two digits at the end, optional. As the literal . is inside the non-captured group with the digits pattern following, it will only be matched when there are required digits afterwards

Demo

Upvotes: 3

Related Questions