0

I'm working on a Celsius to Fahrenheit function in JavaScript and I wrote this code:

<!DOCTYPE html>
<html>
<head>
<title>Celius to Fahrenheit Converter</title>
</head>
<body>

<script type="text/javascript">

alert("Welcome");

function tempConverter() {
var degCent = prompt("Enter the degrees in Farenheit", 50)
var degFahren;

degFahren = 9/5 * (degCent + 32);

alert(degFahren);

}

tempConverter();

</script>

</body>
</html>

I tried using 50 as the default value and when i converted it shows 9057.6 instead of 122. Any Ideas?

1

2 Answers 2

2

You need to convert the input to an integer -

var degCent = parseInt(prompt("enter", 50) , 10);

Sign up to request clarification or add additional context in comments.

Comments

1

The degCent value is being treated as a string. Javascript helpfully does string concatenation when evaluating the expression:

(degCent + 32) = "5032"

Only when starting to do multiplication and division does it then convert the above result to a number to do arithmetic. This is an unexpected (but documented) behaviour of Javascript.

To fix this, force the degCent value to be a number by doing something like:

(+degCent + 32)

The leading + converts the string "50" to a number before adding 32.

3 Comments

thanks for pointing that out, I'm just confused, why is it treating it as a string when the code for my Fahrenheit to Celsius function is working correctly? I have the exact code for it, only the equation is different..
Because <opinion>Javascript has dumb type handling</opinion>. You just have to deal with it, Javascript can't really be fixed at this point.
lol, ok I understand. as a beginner it's just making me so confused right away. Anyway thanks for all the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.