Input Subtraction System With Javascript [duplicate]

1

I have a subtraction system via input only the following is happening for example if the value is 30 and I want to subtract 29.50 instead of 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> 
    
asked by anonymous 23.03.2016 / 16:08

1 answer

3

Use 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> 
    
23.03.2016 / 16:13