Division between integer and real number returns Nan

Asked

Viewed 448 times

5

I’m afraid the integer values (example 350) and a real number (example 3.50), 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.

1 answer

5


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

You need to replace the commas by dots, and to ensure using the function parseFloat 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">

  • Opa thanks was that same, I could also change in the maskmoney of jquery, I used replace to do the calculation and in the input it keeps appearing the comma, thanks @samirbraga, happy new year!

  • You’re welcome, @Brunocabral. Happy New Year to you too :).

Browser other questions tagged

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