JavaScript to convert Fahrenheit to Celsius


This is another School / College program which helps to learn and understand about JavaScript programming. In this example you are going learn to find Celsius from Fahrenheit using pure JavaScript.

There are two versions I have actually written for this post, one will allow any characters in text box and the second will allow only numbers.

Before begin writing the entire program, here is the JavaScript part:

So basically the formula for finding the Celsius is very simple,

c = ( f – 32 ) x 5 / 9

c – celsius
f – fahrenheit

Pass the Fahrenheit value to the formula, so it will give us the Celsius value.
Here is the entire program (1st method, allows any character in the text box):

I have not used alert() to show the output, it is pretty ugly nowadays, so I’m printing the output using JavaScript innerHTML.
Now, the second method which allows only numbers in the text box:

The second method uses another JavaScript function allowOnlyNumber(), which will be initiated onKeyPress in the text box.

Demo for both the programs:

1. Allow any character:


2. Allow only numbers:




Related Posts

4 thoughts on “JavaScript to convert Fahrenheit to Celsius

  1. I couldnt understand this code part, please help

    function allowOnlyNumbers(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode 57)) {
    return false;
    return true;

  2. Hey There,
    I can’t get output for the Following :

    Temp Converter

    Temperature Converter

    var C= parseFloat(prompt(‘Enter temperature in C :’));
    var F= (9*C + 160)/5;
    document.write(“At ” +C “C, Temp. in F is” +F);

Leave a Reply