Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Temperature converter using JavaScript
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
Advertisements