Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx validation of decimal numbers with comma or dot

How to validate such number input with one RegEx. Strings are not allowed. Two decimal positions after dot or comma.

Example:

123.34
1.22
3,40
134,12
123

like image 913
thesis Avatar asked Oct 25 '11 08:10

thesis


4 Answers

Try this regex:

/^(\d+(?:[\.\,]\d{2})?)$/

If $1 exactly matches your input string then assume that it is validated.

like image 196
Aziz Shaikh Avatar answered Sep 25 '22 18:09

Aziz Shaikh


Try This,

/^(\d+(?:[\.\,]\d{1,2})?)$/
like image 30
Om Infowave Developers Avatar answered Sep 24 '22 18:09

Om Infowave Developers


pat = re.compile('^\d+([\.,]\d\d)?$')
re.match(pat, '1212')
<_sre.SRE_Match object at 0x91014a0>
re.match(pat, '1212,1231')
None
re.match(pat, '1212,12')
<_sre.SRE_Match object at 0x91015a0>
like image 23
spicavigo Avatar answered Sep 25 '22 18:09

spicavigo


This is my method to test decimals with , or . With two decimal positions after dot or comma.

  1. (\d+) : one or more digits
  2. (,\d{1,2}|\.\d{1,2})? : use of . or , followed by 2 decimals maximum

const regex = /^(\d+)(,\d{1,2}|\.\d{1,2})?$/;

console.log("0.55 returns " + regex.test('0.55')); //true
console.log("5 returns " + regex.test('5')); //true
console.log("10.5 returns " + regex.test('10.5')); //true
console.log("5425210,50 returns " + regex.test('5425210,50')); //true

console.log("");

console.log("10.555 returns " + regex.test('10.555')); //false
console.log("10, returns " + regex.test('10,')); //false
console.log("10. returns " + regex.test('10.')); //false
console.log("10,5.5 returns " + regex.test('10,5.5')); //false
console.log("10.5.5 returns " + regex.test('10.5.5')); //false
like image 2
Melchia Avatar answered Sep 24 '22 18:09

Melchia