Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript incrementing by 0.5 - how?

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

like image 206
marc_s Avatar asked Feb 24 '13 17:02

marc_s


People also ask

How do you increment a number in JavaScript?

JavaScript has an even more succinct syntax to increment a number by 1. The increment operator ( ++ ) increments its operand by 1 ; that is, it adds 1 to the existing value. There's a corresponding decrement operator ( -- ) that decrements a variable's value by 1 . That is, it subtracts 1 from the value.

Can we increment by 2 in for loop?

A for loop doesn't increment anything.

What is the difference between ++ and += in JavaScript?

++ increases the integer by one and += increases the integer by the number of your choice.

Can you increment a string in JavaScript?

Use the String. fromCharCode() method to increment a letter in JavaScript, e.g. String. fromCharCode(char. charCodeAt(0) + 1) .


2 Answers

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

num += 0.5;
like image 83
nneonneo Avatar answered Nov 11 '22 11:11

nneonneo


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.

like image 34
mavrosxristoforos Avatar answered Nov 11 '22 11:11

mavrosxristoforos