Question:
I'm getting the integer values (example 350) and a real number (example 3.50), I need to divide one by the other, precisely (3.50 / 350) the result would be 0.01.
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
.
Answer:
If the number coming from the text box is formatted with the vírgula
representing the decimal, it won't work. In javascript, this role is the dot .
:
You need to replace the commas with periods, and to ensure 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: <input type="text" value="350" id="tamanho"> <br>Valor: <input type="text" value="3,50" id="valor">