Complete decimal places, "00" JavaScript

0

People I have the following function that I am using to use Currency masks

<input class="valr-parc" type="text" name="valr-parc" />

<script>
    String.prototype.Moeda = function() {
        var v = this;
        v = v.replace(/\D/g,'')
        v = v.replace(/(\d{1})(\d{1,2})$/, "$1,$2")
        v = v.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.')
        v = v.replace(/^(\d)/g,"R$ $1")
        return v;
    }
</script>

<script type="text/javascript">

(function(view) {
    var valr_parc  = document.getElementsByClassName("valr-parc")[0];


    valr_parc.onkeyup =  function(){
        this.value = this.value.Moeda();
    };

})(this);
</script>

I just wanted to implement this function. Moove the following: When I type only a number (ex: 1) it returns "$ 1.00" (currently returns "$ 1") and when I enter 2 numbers (ex: 11) it returns "R $ 1,10" (currently returns "R $ 1.1) hence from these two conditions it can already start to run the way it is (ex: if you type" 111 "returns" R $ 1.11 ", enter" 1111 ">" R $ 11.11 ").

Ah, if you have a different function (that works the same way), you can send it, but please send some example online to test via input (not by "alert" or "console" I did not know how to call the function in other templates (type "function (numero) {...")

    
asked by anonymous 01.11.2017 / 06:06

2 answers

1

Converting numbers to currency without framework

You can convert Number to String currency native, using only the toLocaleString() function. See:

(10.9).toLocaleString(); // "10,90"
(1002.5).toLocaleString("pt-BR"); // "1.002,50"
(5.55).toLocaleString("pt-BR", {
  // Ajustando casas decimais
  minimumFractionDigits: 2,  
  maximumFractionDigits: 2
});

The best of this is that you avoid doing the classic tricks in using Math.abs() or Number.prototype.toFixed() of JavaScript.

And another cool detail, it's safe from floating-point bug:

// Resultado bugado
0.1+0.2 // 0.30000000000000004
// Resultado sem bugs
(0.1+0.2).toLocaleString(); // "0.3"

Functional example for your code:

<input class="valr-parc" type="text" name="valr-parc" />
<button id="verifica">Verificar</buttonbutton>
<script>
    $( document ).ready(function() {
        $("#verifica").on('click', function(){
            var val = new Number ($(".valr-parc").val());
            alert((val).toLocaleString("pt-BR", {
               minimumFractionDigits: 2,  
               maximumFractionDigits: 2
            }));
        })
    });
</script>

link

See more at Number.prototype.toLocaleString ()

    
01.11.2017 / 11:31
1

The simplest solution would be to use the toFixed function.

Here's an example:

var numero = 1;

console.log(numero.toFixed(2));

Note that this function rounds up the numbers in some cases. See this example.

var numero = 1.567;
console.log(numero.toFixed(2));
    
15.10.2018 / 12:13