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

1

6 Answers

Try this regex:

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

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

4

Try This,

/^(\d+(?:[\.\,]\d{1,2})?)$/ 
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> 
1

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
3
Private Sub TexBox_TextChanged(sender As Object, e As EventArgs) Handles TexBox.TextChanged TexBox.Text = System.Text.RegularExpressions.Regex.Replace(TexBox.Text, "[^\d\.]", "") TexBox.Select(TexBox.Text.Length + 1, 1) Dim x As Integer = 0 For Each c In TexBox.Text If c = "." Then x += 1 If (x > 1) Then TexBox.Text = TexBox.Text.Substring(0, TexBox.Text.Length - 1) TexBox.Select(TexBox.Text.Length + 1, 1) End If End If Next End Sub 

A more precise validation over thousands separator and prefix signal:

const re = /^[-\\+]?\s*((\d{1,3}(,\d{3})*)|\d+)(\.\d{2})?$/ console.log(re.test('-1000000.00')) // true console.log(re.test('-1,000,000.00')) // true console.log(re.test('-1000,000.00')) // false 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like