1

I am trying to create a reverse heading app and have gotten the subtraction part of it to work but when I punch in 30 for example instead of pumping out 210 degrees it pumps out 30180. My code is below and I would love some suggestions on how to fix this.

if(convertFromValue > 360){
paraGraph.innerHTML = 'Please enter a number between 1 and 360';
}
else
{
if(convertFromValue > 180) {
paraGraph.innerHTML = convertFromValue - 180 ;

}
else
{
paraGraph.innerHTML = convertFromValue + 180 ;
}
}
}
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
JoshMWilliams
  • 2,254
  • 3
  • 17
  • 14

5 Answers5

8

JavaScript gives preference to strings around the + operator. You have to explicitly make sure that the values are really numbers:

    paraGraph.innerHTML = parseInt(convertFromValue, 10) + 180;

That may or may not be the right thing for your application. There are other common shortcuts to converting strings to numbers. Of course you probably want to check for errors too, because if the string is coming from an input field it might not be (or look like) a number at all.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 2
    +1 for [explicitly setting base 10](http://stackoverflow.com/questions/850341/workarounds-for-javascript-parseint-octal-bug/850346#850346). – Markus Hedlund Sep 29 '11 at 12:58
4

Try

convertFromValue = parseInt(convertFromValue, 10);

before you start checking conditions and adding.

Rob Hruska
  • 118,520
  • 32
  • 167
  • 192
2

You are adding integers to string values, which equates to concatenating the strings together. Use parseInt()

convertFromValue = parseInt(convertFromValue, 10);
if(convertFromValue > 360) {
  paraGraph.innerHTML = 'Please enter a number between 1 and 360';
}
else
{
  if(convertFromValue > 180) {
    paraGraph.innerHTML = convertFromValue - 180 ;
  }
  else
  {
     paraGraph.innerHTML = convertFromValue + 180 ;
  }
}
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
0
paraGraph.innerHTML = parseInt(convertFromValue) + 180 ;
Guillaume
  • 22,694
  • 14
  • 56
  • 70
0

All the answers about needing to use parseInt are correct. This is just a sneaky alternative approach using the + operator to coerce a String to a Number:

paraGraph.innerHTML = +convertFromValue + 180
jmar777
  • 38,796
  • 11
  • 66
  • 64