I have a problem incrementing a number by 0.5. I've used "+=" operator but instead of incrementing my number, this adds "0.5" value in the end of number. The example is this:
<script>
function setTempUp(){
var value = document.getElementById("targetTemp").firstChild.data;
var newvalue = value.replace("°","");
var num = new Number(newvalue);
var num = newvalue += 0.5;
var newtemp = newvalue + '°';
document.getElementById("targetTemp").innerHTML = newtemp;
var cover = document.getElementById('tempChange').clientHeight;
var coverInt = parseInt(cover, 10);
var coverNew = cover - 11;
document.getElementById('tempChange').setAttribute("style","height:" + coverNew + "px");
}
</script>
I'm also "attaching" "°" to my "newTemp", because I have temperature example. Is this a problem?
So, my number is 24 for example - when executed I get "240.5" :(
I have a problem incrementing a number by 0.5. I've used "+=" operator but instead of incrementing my number, this adds "0.5" value in the end of number. The example is this:
<script>
function setTempUp(){
var value = document.getElementById("targetTemp").firstChild.data;
var newvalue = value.replace("°","");
var num = new Number(newvalue);
var num = newvalue += 0.5;
var newtemp = newvalue + '°';
document.getElementById("targetTemp").innerHTML = newtemp;
var cover = document.getElementById('tempChange').clientHeight;
var coverInt = parseInt(cover, 10);
var coverNew = cover - 11;
document.getElementById('tempChange').setAttribute("style","height:" + coverNew + "px");
}
</script>
I'm also "attaching" "°" to my "newTemp", because I have temperature example. Is this a problem?
So, my number is 24 for example - when executed I get "240.5" :(
Share Improve this question edited Feb 24, 2014 at 19:41 tshepang 12.5k25 gold badges97 silver badges139 bronze badges asked Feb 24, 2013 at 17:51 marc_smarc_s 1,0473 gold badges14 silver badges25 bronze badges3 Answers
Reset to default 7newvalue
is a string. Use +=
on your num
directly:
num += 0.5;
You are casting it to a number, but still call the string variable in the following code:
var num = new Number(newvalue);
var num = newvalue += 0.5;
var newtemp = newvalue + '°';
I think that what you meant to do was
var num = new Number(newvalue);
num = num += 0.5;
var newtemp = num + '°';
But whichever it is, you should keep a numeric variable out of the function, and increment that, instead of loading the temperature that you posted on the screen from the last run, and then do it again over and over.
newValue
is a string - returned by value.replace("°","");
Instead of
var num = newvalue += 0.5;
Use
newValue = parseInt(newvalue, 10) + 0.5;
(Since you're not using num
anywhere else, you don't need to assign it any result.)