thesis
thesis

Reputation: 2565

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

Upvotes: 15

Views: 58458

Answers (6)

dgolive
dgolive

Reputation: 437

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

Upvotes: 0

MJT7
MJT7

Reputation: 13

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

Upvotes: 0

Melchia
Melchia

Reputation: 24234

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

Upvotes: 2

Om Infowave Developers
Om Infowave Developers

Reputation: 1565

Try This,

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

Upvotes: 9

Aziz Shaikh
Aziz Shaikh

Reputation: 16524

Try this regex:

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

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

Upvotes: 26

spicavigo
spicavigo

Reputation: 4224

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>

Upvotes: 2

Related Questions