Format cash value while typing with pure javascript

8

There are several questions in the OS about formatting currencies, but most of them are not formatted while a number is typed correctly. How can I format the numbers as you type, passing in these cases below?

For example (input > output):

  

1 > 0.01

     

12 > 0.12

     

123 > 1.23

     

1234 > 12.34

     

12345 > 1.234.50

     

123456 > 1.234.56

     

123456789 > 1.234.567,89

    
asked by anonymous 29.09.2017 / 00:05

2 answers

7

Try this function:

<script language="javascript">   
function moeda(a, e, r, t) {
    let n = ""
      , h = j = 0
      , u = tamanho2 = 0
      , l = ajd2 = ""
      , o = window.Event ? t.which : t.keyCode;
    if (13 == o || 8 == o)
        return !0;
    if (n = String.fromCharCode(o),
    -1 == "0123456789".indexOf(n))
        return !1;
    for (u = a.value.length,
    h = 0; h < u && ("0" == a.value.charAt(h) || a.value.charAt(h) == r); h++)
        ;
    for (l = ""; h < u; h++)
        -1 != "0123456789".indexOf(a.value.charAt(h)) && (l += a.value.charAt(h));
    if (l += n,
    0 == (u = l.length) && (a.value = ""),
    1 == u && (a.value = "0" + r + "0" + l),
    2 == u && (a.value = "0" + r + l),
    u > 2) {
        for (ajd2 = "",
        j = 0,
        h = u - 3; h >= 0; h--)
            3 == j && (ajd2 += e,
            j = 0),
            ajd2 += l.charAt(h),
            j++;
        for (a.value = "",
        tamanho2 = ajd2.length,
        h = tamanho2 - 1; h >= 0; h--)
            a.value += ajd2.charAt(h);
        a.value += r + l.substr(u - 2, u)
    }
    return !1
}
 </script>  
 Entrar caracteres:  <br><br>
 <form>  
 Valor em R$: <input type="text" name="valor" placeholder="Digite aqui" onKeyPress="return(moeda(this,'.',',',event))">  
 </form> 

Source: link .

    
29.09.2017 / 02:00
7

You can use regular expressions for this:

function formatarMoeda() {
  var elemento = document.getElementById('valor');
  var valor = elemento.value;
  
  valor = valor + '';
  valor = parseInt(valor.replace(/[\D]+/g,''));
  valor = valor + '';
  valor = valor.replace(/([0-9]{2})$/g, ",$1");

  if (valor.length > 6) {
    valor = valor.replace(/([0-9]{3}),([0-9]{2}$)/g, ".$1,$2");
  }

  elemento.value = valor;
}
<input type="text" id="valor" onkeyup="formatarMoeda();" />
    
29.09.2017 / 01:07