Fahrenheit to Celsius converter in JavaScript Part II with data validation
In this example will helps you to learn and understand about JavaScript programming on how to get user data and validate that on the run. You’ll also let the user to do multiple conversions before ending the application.
So basically the formula for finding the Celsius is: c = ( f – 32 ) x 5 / 9 where “c” is Celsius and “f” is Fahrenheit.
So below is my HTML code to convert the value into Celsius.
<!doctype html>
<html lang=”en”>
<head>
<title>Convert temperature</title>
<script>
function gettemp(){
var f=prompt(“Enter Fahrenheit temperature”);
fahren=parseFloat(f);
if(fahren===999){ // User will terminate the program using 999
exit;
}else if((fahren < (-100)) || (fahren > 212)){ // user will get alert if value is less then -100 or greater then 212
alert(“You have entered “+fahren+”\n \nPlease enter range from -100 to 212.”);
gettemp();
}else{
var c=parseFloat((fahren-32)*5/9);
alert(“Fahrenheit temperature is “+fahren+”\n \n Celsius temperature is “+c.toFixed(2));
document.getElementById(“convert”).innerHTML = fahren+” Fahrenheit into “+c.toFixed(2)+” Celsius.”;
gettemp(); // call of same function again to run the program in loop
}
}
window.onload=function(){
gettemp();
}
</script>
</head>
<body>
<h1>Thanks for using Temperature Converter App.</h1><br>
<h3>You have last converted <span id=”convert”></span>.</h3>
</body>
</html>
First to run the program on loop we will move basic conversion inside a separate function and do the validation out there. Generally if user enter value less then -100 or greater then 212 it will give alert to user. Also to terminate the program user need to enter value 999 in the prompt box.
Here using prompt(“Enter Fahrenheit temperature”) I’m getting value from user and script will run on window load as function is called inside window.onload .
There is no validation right now to check if user is entering number or not. However we can add that if required. Right now for example we are assuming that user will enter numeric value only.
Once we get the value will convert it into float using .parseFloat() method.
After conversion the float value will be with multiple digits after decimal value, however we need only 2 digits to display after decimal.
To solve this we will call .toFixed() function of JavaScript.
That’s the main concept of getting value from user and converting that to specific result in JavaScript for temperature converter.
Leave a Reply