JavaScript Project : Celsius to Fahrenheit Converter

JavaScript Project : Celsius to Fahrenheit Converter

To become a master in a programming language, you must create some projects. And this is what we are going to do today. Today, we are going to build a simple project which will be based on a Temperature converter. So without wasting time, let's start it :

But before starting it, do you know the maths formula to convert it ? If you don't know, no issue. This is very simple.

    temperature * 9 
    temperature / 5
    temperature + 32

Didn't get it clearly? Suppose, if the user has entered 40 Celsius, so first, we need to :

  • multiply 40 * 9, which will be 360.
  • Then, divide 360 / 5 which will be 72.
  • Now just add 32 in our output i.e. 72. So it would be 104.

So it means user enter the Temperature = 40 Celsius but output will be Temperature = 104 Fahrenheit

Now let's start the coding. Please don't go on styling as we can do it as per our needs. I have mainly focussed on logic. This is our index.html file

raycast-untitled.png

And this is our Output :

temp.png

First, we want to store the temperature value if user enters the input field. To achieve its value. we have given a id utemp to input field in html file.

In the same way, we have also stored the Result value with the id result.

Now, we have to create a function on Button press. For sake of simplicity, we have given the name of function is add().

I hope you understand the html file code so far. Now let's move to logic part i.e. JavaScript.

    <script>


        function add() {

            var temperature = Number(document.getElementById('utemp').value);

            var temperature = temperature * 9;       // 40 * 9 = 360 
            temperature = temperature / 5;            // 360 / 5 = 72    
            temperature = temperature + 32;            // 72 + 32 = 104




            document.getElementById("result").value = temperature;

        }

    </script>

First of all, we need to create a function which should trigger when the user click on Button. So we are creating a function add() and writing our code inside that.

Second, we have declared a variable temperature and storing value from whatever the user types in the first input tag. We have already explained this mathematical formula in this blog.

After applying some maths calculations on user value, we are getting the final value, i.e. 104, we need to show on Result. To achieve this, we just need to target the input tag whose id is result and show the updated value of user input.

Hence, our 40 Celsius value now have coverted to 104 Fahrenheit.