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?

defc0de
  • 25
  • 5
  • 4
    [`prompt()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt) returns a string and [`+`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition) also performs concatenation (`"50" + 32 === "5032"`). [What's the fastest way to convert String to Number in JavaScript?](http://stackoverflow.com/questions/12862624/whats-the-fastest-way-to-convert-string-to-number-in-javascript) – Jonathan Lonowski Jun 02 '15 at 00:34

2 Answers2

2

You need to convert the input to an integer -

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

RaphaelDDL
  • 4,452
  • 2
  • 32
  • 56
rosscj2533
  • 9,195
  • 7
  • 39
  • 56
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.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 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.. – defc0de Jun 02 '15 at 00:42
  • Because Javascript has dumb type handling. You just have to deal with it, Javascript can't really be fixed at this point. – Greg Hewgill Jun 02 '15 at 00:44
  • lol, ok I understand. as a beginner it's just making me so confused right away. Anyway thanks for all the help. – defc0de Jun 02 '15 at 00:48