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" :(
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.
A for loop doesn't increment anything.
++ increases the integer by one and += increases the integer by the number of your choice.
Use the String. fromCharCode() method to increment a letter in JavaScript, e.g. String. fromCharCode(char. charCodeAt(0) + 1) .
newvalue
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With