Reputation: 1047
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" :(
Upvotes: 7
Views: 5232
Reputation: 16215
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.)
Upvotes: 0
Reputation: 3643
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.
Upvotes: 1