Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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().

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading