最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

variables - JavaScript incrementing by 0.5 - how? - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 7

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.

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

发布评论

评论列表(0)

  1. 暂无评论