how to code a BMI using javascript?
toFixed() method.function calculateBMI(weight, height) {
var bmi = weight / (height * height);
return bmi.toFixed(2);
}
var weight = 70; // in kg
var height = 1.75; // in meters
var bmi = calculateBMI(weight, height);
console.log("Your BMI is " + bmi);
<form>
<label for="weight">Weight (in kg):</label>
<input type="number" id="weight" name="weight"><br>
<label for="height">Height (in meters):</label>
<input type="number" id="height" name="height"><br>
<button type="button" onclick="calculate()">Calculate BMI</button>
</form>
<p id="result"></p>
<script>
function calculate() {
var weight = document.getElementById("weight").value;
var height = document.getElementById("height").value;
var bmi = weight / (height * height);
document.getElementById("result").innerHTML = "Your BMI is " + bmi.toFixed(2);
}
</script>
calculate() function is called, which gets the values of weight and height from the input fields, calculates the BMI, and displays the result on the webpage.