JavaScript - formatMoney - How to use

1

How do I make my input stay with the decimal places ....

I need it to format in #total_compra

follow code

<script type="text/javascript">
$(document).ready(function() {

$("#evento_quantidade").change(function() {
var qtd = $(this).val();
var valor = $("#precoSoma").val();
var calculo = qtd * valor;
$("#total_compra").val(calculo);

 });

 String.prototype.formatMoney = function() {
    var v = this;

    if(v.indexOf('.') === -1) {
        v = v.replace(/([\d]+)/, "$1,00");
    }

    v = v.replace(/([\d]+)\.([\d]{1})$/, "$1,$20");
    v = v.replace(/([\d]+)\.([\d]{2})$/, "$1,$2");
    v = v.replace(/([\d]+)([\d]{3}),([\d]{2})$/, "$1.$2,$3");

    return v;
  };
  });
  </script>
    
asked by anonymous 24.06.2017 / 15:49

1 answer

1

You can use toFixed , according to your documentation¹ it:

  

Converts a number into a string, leaving only two decimals.

But of course, you can format for more decimal places if you want. Example:

  var valor = 2000.9001
  valor.toFixed(3) //retorna 2000.900 (arredondamento)
  valor.toFixed(2) //retorna 200.90
  valor.toFixed(7) //retorna 2489.9001000 (preenchimento)

[1] link

    
24.06.2017 / 16:02