How to make my input text have a separator of thousands and decimals in jquery?

11

I am trying to make a coin format for my input, which I want to be formatted automatically with thousand separator (",") and decimals; try with several plugins but they do not work for me.

function addCommas(nStr) {
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    }

This adds me commas, but only for the first unit of thousands: (

This example here works, but in a blur event, as I do to execute it in a keyup event.

$("#number").keyup(function() {

  this.value = parseFloat(this.value.replace(/,/g, ""))
                    .toFixed(2)
                    .toString()
                    .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
});
    
asked by Oscar E. Alvarado 09.09.2016 в 18:30
source

5 answers

16

If you had, for example:

<input id="number">

So, with JQuery 1 :

$("#number").on({
    "focus": function (event) {
        $(event.target).select();
    },
    "keyup": function (event) {
        $(event.target).val(function (index, value ) {
            return value.replace(/\D/g, "")
                        .replace(/([0-9])([0-9]{2})$/, '$1.$2')
                        .replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ",");
        });
    }
});

* See JSFiddle .

Notes

  • Adapted from link
  • answered by 09.09.2016 / 20:47
    source
    6

    Today, most modern browsers support Intl.NumberFormat which helps us to format a number without having to resort to regular expressions or specific jQuery functions.

    To show comma as thousands separator, use it as follows

    var numero = 1E6 + 56 / 100; //Un millón y 56 centésimas
    document
      .getElementById('salida')
      .innerHTML = new Intl.NumberFormat('es-MX').format(numero);
    <div id="salida"></div>

    var numero = 1E6 + 56 / 100; //Un millón y 56 centésimas
    $('#salida').html(new Intl.NumberFormat('es-MX').format(numero));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="salida"></div>
        
    answered by 04.02.2018 в 03:28
    2

    I use for that case jquery.maskedinput.min.js a plugin that formats the input of the input

    A simple example is

    jQuery(function($){
       $("#date").mask("99/99/9999",{placeholder:"mm/dd/yyyy"});
       $("#phone").mask("(999) 999-9999");
       $("#tin").mask("99-9999999");
       $("#ssn").mask("999-99-9999");
    });
    

    In addition to numbers, it allows you to format more input data.

        
    answered by 09.09.2016 в 19:42
    2

    Use jQuery jquery.maskedinput.min.js in the mask function, you give it the format you want your input to have.

    $('#txtMonto').mask('000,000,000.00', { reverse: true });
    
        
    answered by 24.07.2017 в 16:24
    0

    here I leave a function in javascript that allows you to format a number according to a given mask, also the function allows you to process formulate.

    // formatea un numero según una mascara dada ej: "-$###,###,##0.00"
    //
    // elm   = elemento html <input> donde colocar el resultado
    // n     = numero a formatear
    // mask  = mascara ej: "-$###,###,##0.00"
    // force = formatea el numero aun si n es igual a 0
    //
    // La función devuelve el numero formateado
    
    function MASK(form, n, mask, format) {
      if (format == "undefined") format = false;
      if (format || NUM(n)) {
        dec = 0, point = 0;
        x = mask.indexOf(".")+1;
        if (x) { dec = mask.length - x; }
    
        if (dec) {
          n = NUM(n, dec)+"";
          x = n.indexOf(".")+1;
          if (x) { point = n.length - x; } else { n += "."; }
        } else {
          n = NUM(n, 0)+"";
        } 
        for (var x = point; x < dec ; x++) {
          n += "0";
        }
        x = n.length, y = mask.length, XMASK = "";
        while ( x || y ) {
          if ( x ) {
            while ( y && "#0.".indexOf(mask.charAt(y-1)) == -1 ) {
              if ( n.charAt(x-1) != "-")
                XMASK = mask.charAt(y-1) + XMASK;
              y--;
            }
            XMASK = n.charAt(x-1) + XMASK, x--;
          } else if ( y && "$0".indexOf(mask.charAt(y-1))+1 ) {
            XMASK = mask.charAt(y-1) + XMASK;
          }
          if ( y ) { y-- }
        }
      } else {
         XMASK="";
      }
      if (form) { 
        form.value = XMASK;
        if (NUM(n)<0) {
          form.style.color="#FF0000";
        } else {
          form.style.color="#000000";
        }
      }
      return XMASK;
    }
    
    // Convierte una cadena alfanumérica a numérica (incluyendo formulas aritméticas)
    //
    // s   = cadena a ser convertida a numérica
    // dec = numero de decimales a redondear
    //
    // La función devuelve el numero redondeado
    
    function NUM(s, dec) {
      for (var s = s+"", num = "", x = 0 ; x < s.length ; x++) {
        c = s.charAt(x);
        if (".-+/*".indexOf(c)+1 || c != " " && !isNaN(c)) { num+=c; }
      }
      if (isNaN(num)) { num = eval(num); }
      if (num == "")  { num=0; } else { num = parseFloat(num); }
      if (dec != undefined) {
        r=.5; if (num<0) r=-r;
        e=Math.pow(10, (dec>0) ? dec : 0 );
        return parseInt(num*e+r) / e;
      } else {
        return num;
      }
    }
    ingresar un valor numero (o formula) formatear con -$##,###,##0.00<br>
    <input onchange="MASK(this,this.value,'-$##,###,##0.00',1)"><br>
    <br>
    ingresar un valor numero (o formula) formatear con 00/00/0000<br>
    <input onchange="MASK(this,this.value,'00/00/0000',1)"><br>
        
    answered by 30.06.2017 в 01:03