How to Convert Temperature in Fahrenheit to Celsius using JavaScript?

Today we are going to learn how to convert Fahrenheit to Celsius using JavaScript.

We mostly use Fahrenheit and centigrade as the two temperature scales in our daily life. Daniel Gabriel Fahrenheit developed the Fahrenheit scale. Here water freezes at 32 degrees and boils at 212 degrees.

Swedish astronomer Andres Celsius developed the centigrade scale. The centigrade to Fahrenheit conversion formula is:

C = (5/9)*(F-32)

CONVERT A TEMPERATURE IN FAHRENHEIT TO CELSIUS USING JAVASCRIPT

It is very easy to convert the temperature from Fahrenheit to Celsius. The only thing that you need to keep in mind is how to use the predefined functions while writing the JavaScript code. For your convenience I will write both the HTML and the JAVASCRIPT codes below, first separately and then will give you the entire code, so that it is easy for you to understand.

HTML CODE

In this HTML code at first, we create an input element converts a value from one temperature unit to another. In this code, the input element will convert a temperature in  Fahrenheit to Celsius.

<!DOCTYPE html> 
<html>
 <title>Fahrenheit to Celsius</title>
 <body>
 <h2>Temperature Converter</h2>
 <p>Enter the value in the Fahrenheit :</p>
 <p> <label>Fahrenheit</label>
 <input id="inputF" type="number" placeholder="F" oninput="temperatureChange(this.value)" onchange="temperatureChange(this.value)">
 </p>
 <p>Celsius: <span id="outputC"></span></p>
</body>
 </html>

 

JAVASCRIPT CODE

The input field receives the input which convert the value from Fahrenheit to Celsius. We define a function “temperatureChange” for our purpose.

<script>
 function temperatureChange(valNum) { valNum = parseFloat(valNum); document.getElementById("outputC").innerHTML=(valNum-32)/1.8; }
 </script>

 

Convert Temperature in Fahrenheit to Celsius using JavaScript

We have to insert the JavaScript code into the above HTML code and we use the script tag to do this.

<!DOCTYPE html> 
<html>
 <title>Fahrenheit to Celsius</title>
 <body>
 <h2>Temperature Converter</h2>
 <p>Enter the value in the Fahrenheit :</p>
 <p> <label>Fahrenheit</label>
 <input id="inputF" type="number" placeholder="F" oninput="temperatureChange(this.value)" onchange="temperatureChange(this.value)">
 </p>
 <p>Celsius: <span id="outputC"></span></p>
 <script>
 function temperatureChange(valNum) { valNum = parseFloat(valNum); document.getElementById("outputC").innerHTML=(valNum-32)/1.8; }
 </script>
 </body>
 </html>

 

OUTPUT

Initial

If we enter the value as 32 in Fahrenheit.

Fahrenheit: 32

Celsius:

Final

We get the value in Celsius as 0

Fahrenheit: 32

Celsius: 0

 

So you can see how easy and fun this code was. You can try out this example yours and may also read

Leave a Reply

Your email address will not be published. Required fields are marked *