Temperature converter using JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a string representing a temperature either in Celsius or in Fahrenheit.

Like this −

"23F", "43C", "23F"

We are required to write a JavaScript function that takes in this string and converts the temperature from Celsius to Fahrenheit and Fahrenheit to Celsius.

Example

Following is the code −

const temp1 = '37C';
const temp2 = '100F';
const tempConverter = temp => {
   const degree = temp[temp.length-1];
   let converted;
   if(degree === "C") {
      converted = (parseInt(temp) * 9 / 5 + 32).toFixed(2) + "F";
   }else {
      converted = ((parseInt(temp) -32) * 5 / 9).toFixed(2) + "C";
   };
   return converted;
};
console.log(tempConverter(temp1));
console.log(tempConverter(temp2));

Output

Following is the output in the console −

98.60F
37.78C
raja
Published on 18-Sep-2020 12:46:58
Advertisements