# How to Convert Fahrenheit to Celsius in JavaScript

## Fahrenheit to Celsius converter in JavaScript

This example of converting Fahrenheit to Celsius in JavaScript will helps you to learn and understand about JavaScript programming. In this example you are going learn to find Celsius from Fahrenheit using pure JavaScript while taking value input from users. I have used JavaScript prompt to take the value from user however you can use simple HTML form to get the value and display the results.

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>
window.onload=function(){

var f=prompt(“Enter Fahrenheit temperature”);
fahren=parseFloat(f);
var c=parseFloat((fahren-32)*5/9);  // Coniversion of Fahrenheit into celcius

alert(“Fahrenheit temperature is “+fahren+”\n \n Celsius temperature is “+c.toFixed(2));  // display result into alert format.

document.getElementById(“convert”).innerHTML = fahren+” Fahrenheit into “+c.toFixed(2)+” Celsius.”;  // Display the result in html
}
</script>
</head>
<body>
<h1>Thanks for useing Temperature Converter App.</h1><br>
<h3>You have converted <span id=”convert”></span>.</h3>
</body>
</html>

here using prompt(“Enter Fahrenheit temperature”) I’m getting value from user and script will run on window load and function is called on 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.

### Share this post

This site uses Akismet to reduce spam. Learn how your comment data is processed.