【问题标题】:I need to have this JavaScript function only output integers我需要让这个 JavaScript 函数只输出整数
【发布时间】:2021-11-06 02:24:40
【问题描述】:
<html>

<script>


function fahrenheitToCelcius(temp) {
    return (parseFloat(temp) - 32) * (5 / 9);
}

function isNumber(value) {
    return typeof (value) != "boolean" && !isNaN(value) && value.length > 0;
}

function minMaxTemp(value, min, max, unit) {
    console.log("function called");
    if (value.length == 0 || value == "-") return value;
    if (!isNumber(value)) return value.substring(0, value.length - 1);

    if (unit == 1) value = fahrenheitToCelcius(value);

    if (parseFloat(value) < min)
        return min;
    else if (parseFloat(value) > max)
        return max;
    else return value;

}
</script>

<table class="center">
    
      <tr>
        <th>Setpoint</th>
        <th><input id="setPoint" type="text" name="setPoint" value="4" onkeyup="this.value = minMaxTemp(this.value, -80, 150, 0)"   /></th>
       
      </tr>
</table>
</html> 
  • 该代码正在处理最小值和最大值,但它仍然输出我不希望它输出的小数点值,即 4.5
  • 该函数必须只输出整数,即 4 ,5, 7 而不是例如 4.0, 5.8, 7.6
  • 下面是带有 web 表单和 javascript 函数的代码
  • 感谢您提供的任何帮助

【问题讨论】:

  • 您的代码有什么问题?您没有具体说明任何实际问题,我们很难为您提供帮助。

标签: javascript html webforms


【解决方案1】:

根据您是要向下取整还是向上取整,您可以使用Math.floor()Math.ceil()

<th><input id="setPoint" type="text" name="setPoint" value="4" onkeyup="this.value = Math.floor(minMaxTemp(this.value, -80, 150, 0))"   /></th>

MDN 文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor

【讨论】:

    【解决方案2】:

    由于从您的预期输出来看,您希望小数四舍五入,我建议使用 JavaScript 的 Math.floor 函数将值向下舍入到最接近的整数

    Math.floor(3.712)
    

    将返回值 3

    【讨论】:

      猜你喜欢
      • 2017-08-18
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 2020-09-08
      • 1970-01-01
      • 2012-11-19
      • 2013-06-03
      • 1970-01-01
      相关资源
      最近更新 更多