0

I' ve made this simple form which calculates the BMI from Height and Weight Variables. It works when i insert integers to Height and Weight variables respectively, but unfortunately it doesn't work the way it should when i insert decimal numbers.

Any thoughts on fixing this issue?

function Calculate() {
  var manWeight = document.getElementById('manWeight').value;
  var manHeight = document.getElementById('manHeight').value;

  document.getElementById('manBMI').value = parseInt(document.getElementById('manWeight').value) / Math.pow(parseInt(document.getElementById('manHeight').value), 2);
  
}
<label for="manWeight">Weight: *</label>
  <input type="text" name="manWeight" size="35" id="manWeight" required autocomplete="off">
  <br>

<label for="manHeight">Height: *</label>
  <input type="text" name="manHeight" size="35" id="manHeight" required autocomplete="off"> <br>

<label for="manBMI">BMI:</label>
  <input type="text" name="manBMI" size="35" id="manBMI" required disabled autocomplete="off">

<button type="button" id="calculator" name="calculator" onclick="Calculate();">Calculate</button>

1
  • Cerbrus can you please explain me how am i supposed to know that the root of my problem could be found in that article? And you also downvote a fair answer. Stack Overflow is built to make our lives simpler not more complex, especially for us who are self taught developers ... Commented Dec 8, 2017 at 14:14

1 Answer 1

0

You don't need to use parseInt(value) when calculating the final values. parseInt will round down any floats that you can pass in.

You can instead use Number(value). Which will parse floats. But this will return NaN if you input invalid characters.

You can use the input type of Number in limit the inputs to valid numbers. (on supported browsers)

function Calculate() {
  var manWeight = document.getElementById('manWeight').value;
  var manHeight = document.getElementById('manHeight').value;

  document.getElementById('manBMI').value = Number(document.getElementById('manWeight').value) / Math.pow(Number(document.getElementById('manHeight').value), 2);
  
}
<label for="manWeight">Weight: *</label>
  <input type="number" name="manWeight" size="35" id="manWeight" required autocomplete="off">
  <br>

<label for="manHeight">Height: *</label>
  <input type="number" name="manHeight" size="35" id="manHeight" required autocomplete="off"> <br>

<label for="manBMI">BMI:</label>
  <input type="text" name="manBMI" size="35" id="manBMI" required disabled autocomplete="off">

<button type="button" id="calculator" name="calculator" onclick="Calculate();">Calculate</button>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot @nipuna777 ! I used the first answer of yours which worked perfectly, i'm not the one who downvoted ...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.