Javascript - formatMoney - How to use

Asked

Viewed 661 times

1

How do I make my input stick to the decimals....

I need it to format at #total_buy

follows 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>

1 answer

1


You can use toFixed , according to his documentation¹ he :

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

But of course, you can format to more decimals 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] https://www.w3schools.com/jsref/jsref_tofixed.asp

  • That’s right, but how do I apply it to my code?

  • Look at this example : https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tofixed

  • good Ek mto obg.... solved

Browser other questions tagged

You are not signed in. Login or sign up in order to post.