-4

This question has an answer:

see - Javascript variables not adding two variables correctly, only concatenating

I am trying to add 5 units to a number but the number is being concatenated instead.

 this.graphicState[i].shapes[j][k].x += 5

Each time this is run in a loop the outputs are

105.00
105.005
105.0055
105.00555
...

The output I am looking for is,

105.00
110.00
115.00
120.00
...

I tried,

this.graphicState[i].shapes[j][k].x += parseFloat(5)

I also tried this, but get the same results,

this.graphicState[i].shapes[j][k].x = this.graphicState[i].shapes[j][k].x + 5

Thanks,

Shane G
  • 3,129
  • 10
  • 43
  • 85
  • 2
    looks like you add something to a string, not a number. why not keep the value of `this.graphicState[i].shapes[j][k].x` as number and use later a fixed value. – Nina Scholz Oct 10 '18 at 12:02
  • I thought parseFloat() would fix that. But it doesn't, thanks – Shane G Oct 10 '18 at 12:04
  • @ShaneG It could, but not the way you used it . You can use your last example, and parseFloat the `this.graphicState[i]....` of the right side . – sagi Oct 10 '18 at 12:05

2 Answers2

2

You need to convert any/all string values to numbers in an expression that has strings as operands with + as the operator. The 5 isn't the issue, this is:

this.graphicState[i].shapes[j][k].x

So, that's what needs to be converted. You can do that easily by prepending a + to it:

+this.graphicState[i].shapes[j][k].x;

Do the conversion on the string first and then use the converted value in your mathematical expression. Here's a simplified example:

var result = "5"
result = +result + 10;
console.log(result);
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
1

Try this method

this.graphicState[i].shapes[j][k].x = (parseFloat(this.graphicState[i].shapes[j][k].x) + 5).toFixed(2);
NIDHIN VINCENT
  • 225
  • 1
  • 2
  • 9