Division between integer and real returns NaN

5

I'm not sure how to do this:

var tamanho = parseInt($("#tamanho").val());
var valor = $("#valor").val();
var valorMl = valor / tamanho;
console.log(valor, tamanho, valorMl);

valor returns 3,50 .

tamanho returns 350 .

valorMl returns NaN .

    
asked by anonymous 31.12.2016 / 17:00

1 answer

5

If the number coming from the text box is formatted with vírgula representing the decimal, it will not work. In javascript, this role is the point . :

You need to replace the commas with points, and to ensure that you use the parseFloat function that always returns a number:

function calc() {
  var tamanho = parseInt($("#tamanho").val());
  var valor = parseFloat($("#valor").val().replace(/\,/, '.'));
  var valorMl = valor / tamanho;
  console.log(valor, tamanho, valorMl);
}

calc();

$("#tamanho, #valor").on('input', calc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Tamanho:<inputtype="text" value="350" id="tamanho">
<br>Valor:
<input type="text" value="3,50" id="valor">
    
31.12.2016 / 17:07