Sum with decimals

1

I am trying to make a sum with decimals, I am starting to use javascript to make operations etc.

this is the script I use:

<script>
  function sumar (valor) {
    var total = 0;  
    valor = parseInt(valor); // Convertir el valor a un entero (número).

    total = document.getElementById('spTotal').innerHTML;

    // Aquí valido si hay un valor previo, si no hay datos, le pongo un cero "0".
    total = (total == null || total == undefined || total == "") ? 0 : total;

    /* Esta es la suma. */
    total = (parseInt(total) + parseInt(valor));

    // Colocar el resultado de la suma en el control "span".
    document.getElementById('spTotal').innerHTML = total;
}
</script>

How can I use that code to do them with decimals and not just with integers?

    
asked by cesg.dav 10.07.2017 в 02:31
source

2 answers

2

To be able to obtain the valor in decimals you must use parseFloat instead of parseInt , otherwise you will lose the decimals and you will convert to integer. Therefore, change parseInt(valor) by parseFloat(valor) .

    
answered by 10.07.2017 / 03:11
source
0

parseInt convert the values to integers, instead of that use parseFloat .

Below is an example based on the code of the question. The original lines that should be changed I have commented and then the proposed change.

function sumar(valor) {
  var total = 0;
  //valor = parseInt(valor); // Convertir el valor a un entero (número).
  // total = document.getElementById('spTotal').innerHTML;

  total = parseFloat(document.getElementById('spTotal').innerHTML);

  // Aquí valido si hay un valor previo, si no hay datos, le pongo un cero "0".
  total = (total == null || total == undefined || total == "") ? 0 : total;

  /* Esta es la suma. */
  // total = (parseInt(total) + parseInt(valor));
  total += parseFloat(valor);

  // Colocar el resultado de la suma en el control "span".
  document.getElementById('spTotal').innerHTML = total;
}
<input type="number"/><br/>
<input type="button" value="Sumar" onclick="let valor = document.querySelector('input[type=number]').value; sumar(valor);"/><br/>
<div id="spTotal">0</div>
    
answered by 10.07.2017 в 03:25