mattdaspy
mattdaspy

Reputation: 882

JavaScript issue, Celsius to Kelvin not working

The whole rest of convertions work, but the only 2 with the Kelvin unit don't work properly, instead of calculating the numbers, it just shows the result with the entry added before the value.

Example :. 32ºC to K would be 305.15

Issue :. It shows 32273.15

The same happens from Kelvin to Celsius.

function conv_temp() {

//Get values of entries from the form
var n = document.getElementById("temp").value;  // Text field
var u1 = document.getElementById("t1").value;   // First temperature unit choice
var u2 = document.getElementById("t2").value;   // Second temperature unit choice

var ctk = (n + 273.15);             // Celsius to Kelvin
var ktc = (n - 273.15);             // Kelvin to Celsius

//Move decimals accordingly to temperature unit
var resctk = ctk.toFixed(2);
var resktc = ktc.toFixed(1);

if (u1 == "2" && u2 == "3") { // ºC to K

    document.getElementById("res_temp").innerHTML = resctk;
    document.getElementById("unit").innerHTML = " K";
    document.getElementById("result").style.display = "block";
    document.getElementById("result").style.visibility = "visible";
    return true;

}

else if (u1 == "3" && u2 == "2") { // K to ºC

    document.getElementById("res_temp").innerHTML = resktc;
    document.getElementById("unit").innerHTML = " ºC";
    document.getElementById("result").style.display = "block";
    document.getElementById("result").style.visibility = "visible";
    return true;

}

else {return true;}

}

What should I do ? Tried to change the variables and also from variables to the exact number (273.15), none of it works

Upvotes: 1

Views: 498

Answers (1)

Kapulara
Kapulara

Reputation: 301

First you have to parse the temp as a number before you can perform math operations on it

var n = parseFloat(document.getElementById("temp").value);

Upvotes: 4

Related Questions