| Viewed 124 times

Temperature Converter in javaScript?


I need to create a function that converts Celcius to Fahrenheit and vice versa. Examples convert("35°C") // "95°F" convert("19°F") // "-7°C" convert("33") //"Error"

1 Answer
Mohammad Qandeel
Answered
10

try this function, it will convert Celcius to Fahrenheit and vice versa.

function convert(deg){
 var temp = deg.split("°")[0];
 if (deg[deg.length - 1] == "F"){
  return String(Math.round((+temp - 32) * 5/9)) + "°C"
 }
 else if (deg[deg.length - 1] == "C"){
  return String(Math.round(+temp * 9/5 + 32)) + "°F";
 }
 else { return "Error" };
}

Example

convert('6°F') //"-14°C"

convert('6°C') //"43°F"



Related Questions