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 ;
}
}
}
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 ;
}
}
}
Share
Improve this question
edited Dec 8, 2013 at 4:42
Josh Crozier
241k56 gold badges400 silver badges313 bronze badges
asked Sep 29, 2011 at 12:53
JoshMWilliamsJoshMWilliams
2,3843 gold badges17 silver badges15 bronze badges
0
5 Answers
Reset to default 8JavaScript 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 mon shortcuts to converting strings to numbers. Of course you probably want to check for errors too, because if the string is ing from an input field it might not be (or look like) a number at all.
Try
convertFromValue = parseInt(convertFromValue, 10);
before you start checking conditions and adding.
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 ;
}
}
paraGraph.innerHTML = parseInt(convertFromValue) + 180 ;
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