In: Computer Science
Write a javascript program according to the follow requirements:
function convert(isFtoC, from, to) {
// your code here
}
Note: Use .toFixed(2) to limit the decimal digits to 2, e.g. num.toFixed(2)
Dear Student ,
As per the requirement submitted above , kindly find the below solution.
Here a new web page with name "tempConversion.html" is created, which contains following code.
tempConversion.html :
<!DOCTYPE html>
<html lang="en">
<head>
<!-- title for web page -->
<title>Temprature Conversion</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
From Temp :<input type="text" id="txtFrom"/>
<br><br>
To Temp :<input type="text" id="txtTo"/>
<br><br>
Select Conversion :
<select id="temp">
<option selected>--Select Conversion--</option>
<option value="Fahrenheit">Fahrenheit</option>
<option value="Celsius">Celsius</option>
</select>
<br><br>
<input type="button" onclick="convertTemp()" value="Convert"/>
<!-- div to display temprature -->
<div id="myDiv"></div>
<!-- <script> is used for javascript -->
<script>
//function to convert temprature
function convertTemp()
{
var from=parseFloat(document.getElementById("txtFrom").value);//take from temp
var to=parseFloat(document.getElementById("txtTo").value);//take to temp
//checking what is selected
if(document.getElementById("temp").value=="Fahrenheit")
{
//if Fahrenheit is selected
convert(true,from,to);
}
else{
//if Celisus is selected
convert(false,from,to);
}
}
//function to convert Fahrenheit to Celsius
function fToC(f)
{
return (f-32)* 5/9;//return temp in c
}
//function to convert Celsius to Fahrenheit
function cTof(c)
{
return (c*9/5)+32;//return temp in f
}
//function to convert temprature
function convert(isFtoC, from, to)
{
var tempStr="";
//checking if Fahrenheit to Celsius
if(isFtoC==true)
{ tempStr="F:C<br/>";
//convert temprature in Fahrenheit
for(var i=from;i<=to;i++)
{
tempStr+=i+" : "+fToC(i).toFixed(2)+"<br/>";//call function and concate
}
show(tempStr);//call function to display details
}
else if(isFtoC==false){
tempStr="C:F<br/>";
for(var i=from;i<=to;i++)
{
tempStr+=i+" : "+cTof(i).toFixed(2)+"<br/>";//call function and concate
}
show(tempStr);//call function to display details
}
}
//function to show string
function show(str)
{
document.getElementById("myDiv").innerHTML=str;//display on the div
}
</script>
</body>
</html>
======================================================
Output : Compile and Run tempConversion.html in the browser and will get the screen as shown below
Screen 1 :tempConversion.html
Screen 2 :Temp from f to c
Screen 3 :Temp from c to f
NOTE : PLEASE FEEL FREE TO PROVIDE FEEDBACK ABOUT THE SOLUTION.