Jump to content

Numbers are concatenating instead of adding


Choeeey
 Share

Recommended Posts

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

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.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...