7

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" :(

tshepang
  • 12,111
  • 21
  • 91
  • 136
marc_s
  • 1,007
  • 3
  • 14
  • 24

3 Answers3

7

newvalue is a string. Use += on your num directly:

num += 0.5;
nneonneo
  • 171,345
  • 36
  • 312
  • 383
1

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.

mavrosxristoforos
  • 3,573
  • 2
  • 25
  • 40
0

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.)

Krease
  • 15,805
  • 8
  • 54
  • 86
  • This still has the issue of the double assignment, which throws an error. – Giles Feb 24 '13 at 17:58
  • @Giles - that just updates `num`, which is not used again in the function - additional declarations of `var num` have no effect - see http://stackoverflow.com/a/14010168/836214 – Krease Feb 24 '13 at 18:02
  • sorry, it's not the double assignment that's causing the error, it's the fact that you can't increment the function `parseInt` by 5. – Giles Feb 24 '13 at 18:51
  • Ah - you mean the result of `parseInt` because it's not a variable, so it's an invalid assignment. That's what I get for not running code in an answer before I post it. I'll update it. – Krease Feb 24 '13 at 18:58