Regular expression decimal numbers

1

I am trying to create a regular expression for you to accept that type of numbering

  • 1,111,111,0000
  • 111,111,0000
  • 0.0000
  • 111.1111
  • The expression he was using was the following

      

    [0-9] {1,2} [.] [0-9] {1,3} [.] [0-9] {1,3} [] \ d *

    That expression only accepts 1,111,111,0000 but I'm trying to take the other cases. help!

        
    asked by Alvarows 06.07.2018 в 21:39
    source

    1 answer

    1

    In your regular expression

    [0-9]{1,2}[.][0-9]{1,3}[.][0-9]{1,3}[,]\d*
    

    are you saying:

  • One or two numeric digits followed by a dot
  • Followed by one, two or three numeric digits and another point
  • Followed by one, two or three numeric digits and a comma
  • Optionally , followed by N decimals
  • That is inconsistent. First, because you are demanding that the number be large enough to have two thousand separators. Second, because you require the decimal separator, when a whole number does not have to have it. Third, because if the number is larger, and it has three thousand separators, it does not fit. Fourth, because the separator of thousands occurs every 3 digits, not every "one to three digits".

    A regular expression of the type:

    /^\d{1,3}(\.\d{3})*(,\d+)?$/
    

    Means instead:

  • One to three digits
  • Followed by zero or more occurrences of .###
  • Optionally followed by a decimal point and more than one decimal
  • This means that, for example, 1.000, does not comply. The comma makes no sense if there are no decimals.

    Let's try it:

    var numeros = ['1.111.111,0000',
    '111.111,0000',
    '0.0000',
    '111.1111'];
    
    numeros.forEach(function(numero) {
    
     if(/^\d{1,3}(\.\d{3})*(,\d+)?$/.test(numero)) {
       console.log(numero, 'SÍ calza');
     } else {
       console.log(numero, 'NO calza');
     }
    
    });

    If you notice, 0.0000 does not fit, because there are four figures together without a separator of thousands in between. It should be 00.000 . (Although accepting zeros to the left does not really have any purpose ...)

    111.1111 does not fit, for the same reason. It should be 1.111.111 .

    The thousands separator will always require three numbers and only three numbers below.

    If you want to accept numbers formatted with both the Latin system (points to separate thousands, to separate the decimal part) and the English system (just the other way around) you should make two regular expressions and try to fit one or the other. Otherwise you will have an inconsistent expression that allows you to mix uncompleted dots and commas.

        
    answered by 07.07.2018 / 00:54
    source