Choeeey Posted February 9, 2015 Share Posted February 9, 2015 this.score=this.game.time.totalElapsedSeconds().toFixed(0); this.score = this.score+5; say the first this.score = 5.I want the next this.score to equal 10. But instead, I get 55. I looked up the API, and it says this.score should be a number so I cannot understand why this is happening? Link to comment Share on other sites More sharing options...
Anderberg Posted February 9, 2015 Share Posted February 9, 2015 toFixed will return a string, that is why you get contatenation instead of addition. (source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed)You want to use Math.floor(this.game.time.totalElapsedSeconds()) instead. Choeeey 1 Link to comment Share on other sites More sharing options...
Choeeey Posted February 9, 2015 Author Share Posted February 9, 2015 Whoops! Thank you Link to comment Share on other sites More sharing options...
totallybueno Posted February 9, 2015 Share Posted February 9, 2015 And you can also check http://www.w3schools.com/jsref/jsref_parseint.asp Choeeey 1 Link to comment Share on other sites More sharing options...
ikkuh Posted February 9, 2015 Share Posted February 9, 2015 Math.floor( ... );Notice that 'toFixed' rounds numbers instead of flooring them. As described in your link: "... The number is rounded if necessary, ..." Of course 'Math.floor' might be exactly what Choeeey wants, but 'Math.round' gives the correct behavior of 'toFixed'. Choeeey and Anderberg 2 Link to comment Share on other sites More sharing options...
mwatt Posted February 9, 2015 Share Posted February 9, 2015 There are a number of different tricks you can use to force addition instead of concatenation. Math.floor is one. When I was "growing up" with JavaScript (heh, loooong time ago), I used to do things like subtracting a minus or multiplying * -1. Hahah, cheesey, but it works. Another thing that is useful when concatenating several strings on a line but two of the strings are meant to be added together is to parenthesize the two strings being added. There are some bit shifting tricks too I think... but in any event, the overall most performant and most standard solution is parseInt (or parseFloat if necessary). In specific cases, things like Math.floor or Math.round are more natural. Choeeey 1 Link to comment Share on other sites More sharing options...
tips4design Posted February 9, 2015 Share Posted February 9, 2015 Easier:this.score = this.game.time.totalElapsedSeconds() | 0;This does a btiwise or between the float number and 0, which converts the number to an integer. This is usually the correct way to solve your problem.This also is the fastest way do do it (performance wise). Choeeey 1 Link to comment Share on other sites More sharing options...
Recommended Posts