Input Subtraction System With Javascript

Asked

Viewed 1,448 times

1

I have a subtraction system via input only that the following is happening for example if the value is 30 and I want to subtract 29.50 instead of appearing 0.50 it appears 0.5 does not appear 0 at the end, and also if it is 29.60 and I want to subtract 29.50 instead of appearing 0.10 it appears 0.10000000000000142

the code is this

<script language="javascript">
            function calcular(){
                var valor1 = document.getElementById("valor1").value; //pega o valor do imput do valor 1
                var valor2 = document.getElementById("valor2").value; //pega o valor do imput do valor 2
                var subtracao = valor1 - valor2; //calcula =D

                //insere no html da div subtraçao o imput com o valor da calculo
                document.getElementById("subtracao").innerHTML = "<span class='info-box-number'>"+ subtracao +""+'R$' +" </span>";
            }
        </script> 

1 answer

3


Use the toFixed(2)

<script language="javascript">
            function calcular(){
                var valor1 = document.getElementById("valor1").value; //pega o valor do imput do valor 1
                var valor2 = document.getElementById("valor2").value; //pega o valor do imput do valor 2
                var subtracao = parseFloat(valor1 - valor2).toFixed(2); //calcula =D

                //insere no html da div subtraçao o imput com o valor da calculo
                document.getElementById("subtracao").innerHTML = "<span class='info-box-number'>"+ subtracao +""+'R$' +" </span>";
            }
</script> 

Browser other questions tagged

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