简体   繁体   中英

BMI calculator how to round up to 1 d.c.?

I'm creating a BMI calculator project, and I'm almost finished. Just one thing I don't know how to do is how to round the result to 1 dc

Also I don't why the calculate button didn't work after I copy and paste to here. The code is below:

<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>BMI Calculator</title>
</head>

<script language="JavaScript">

function calculateBmi() {

var weight = document.bmiForm.weight.value
var height = document.bmiForm.height.value

if(weight > 0 && height > 0){   

var finalBmi = weight/(height/100*height/100)
document.bmiForm.bmi.value = finalBmi

 if(finalBmi <=18.5){
document.bmiForm.meaning.value = "過輕"
}
else if(finalBmi >=18.5 && finalBmi <=22.9){
document.bmiForm.meaning.value = "體重正常"
}
else if(finalBmi >=23 && finalBmi <=24.9){
document.bmiForm.meaning.value = "過重"
}
else if(finalBmi >=25 && finalBmi <=29.9){
document.bmiForm.meaning.value = "肥胖"
}
else if(finalBmi >=30){
document.bmiForm.meaning.value = "太肥胖"
}
}
else {
alert("你忘了輸入呀!!")
}
}
</script>
<body>
<form name="bmiForm">
你的體重(kg): <input type="text" name="weight"><br />
你的身高(cm): <input type="text" name="height"><br />
<input type="button" value="Calculate BMI" onClick="calculateBmi()">
<input type="reset" value="Reset" /><br/>
你的BMI: <input type="text" name="bmi"><br />
你的健康狀況: <input type="text" name="meaning"><br />
</form>
<table border="1" >
 <tr>
 <td width="100" align="center" bgcolor="#FFFF00">組別 </td>
 <td width="100" align="center" bgcolor="#FFFF00">BMI</td>
 </tr>
 <tr>
 <td width="100" align="center">過輕 </td>
 <td width="100" align="center">&lt;18.5</td>
 </tr>
 <tr>
 <td width="100" align="center">體重正常 </td>
 <td width="100" align="center">18.5 - 22.9</td>
 </tr>
 <tr>
 <td width="104" align="center">過重 </td>
 <td width="113" align="center">23 - 24.9</td>
 </tr>
 <tr>
 <td width="104" align="center">肥胖 </td>
 <td width="113" align="center">25 - 29.9</td>
 </tr>
 <tr>
 <td width="104" align="center">太肥胖 </td>
 <td width="113" align="center">30 &amp; above</td>
 </tr>
</table>
</body>
</html>

Assuming you want to round off to one decimal, you can use .toFixed() on a number:

var BMI = 123.5456;
console.log(BMI.toFixed(1));

// output
123.5

The one thing to keep in mind is the this returns a string, to convert back to number wrap the result with parseFloat()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM