I need to have this JavaScript function only output integers

<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> 
  • the code is fucntioning for min and max values but it still outputs decimal point values which i dotn want it to doo ie 4.5
  • the function must only output integers ie 4 ,5, 7 not for example 4.0, 5.8, 7.6
  • below is the code with a web form and javascript function
  • thank you for any help provided

>Solution :

Depending on whether you want to round down or round up, you can use Math.floor() or 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 docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor

Leave a Reply