BMI 计算器如何四舍五入到 1 DC

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

本文关键字:DC 四舍五入 计算器 BMI      更新时间:2023-09-26

我正在创建一个BMI计算器项目,我快完成了。我不知道该怎么做的一件事是如何将结果四舍五入为 1 d.c。

我也不知道为什么在我复制并粘贴到这里后计算按钮不起作用。代码如下:

<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>

假设你想四舍五入到一个小数点后,你可以对一个数字使用.toFixed()

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

要记住的一件事是 this 返回一个字符串,要转换回数字包装

结果,parseFloat()