2

I am receving JSON from server and have to add or substract some numbers, but it does not work for adding, but for substracting it does. Any idea why?

data = {
  point: {
    x: '4.0',
    y: '10.0'
  }
}

startX = 10;
startY = 5;

newX= startX + data.point.x;
newY= startY - data.point.y;

console.log(newX, newY)
john smith
  • 31
  • 4

2 Answers2

2

You need to convert the string to a number, because strings a possible to add, which means concat. By taking - both operands are converted to number.

var data = { point: { x: '4.0', y: '10.0' } },
startX = 10,
startY = 5,
newX = startX + +data.point.x,
newY = startY - +data.point.y;

console.log(newX, newY)
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 1
    The `+` cast hack is cute but obscure. Recommend [`parseInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt)/[`parseFloat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat) for clarity. – André Dion Mar 21 '19 at 12:56
  • 4
    [unary plus `+`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus) is not a hack, but a language feature. – Nina Scholz Mar 21 '19 at 12:59
  • unary plus is often used and is considered strongly semantic as casting boolean with double `!!` – Mosè Raguzzini Mar 21 '19 at 13:06
0

That's because you're numbers from the JSON are treated as strings not numbers. You need to convert them to numbers (integer or float) first.

newX = startX + parseFloat(data.point.x);
newY = startY - parseFloat(data.point.y);
obscure
  • 11,916
  • 2
  • 17
  • 36
  • Since JS only has a single numeric format, you'd only convert to that, not to integer or a float. The `parseInt` function just stops parsing when it encounters a non-integer character and `.` is one. That is a valid character for `parseFloat`, though. Point is, they don't produce two different types, but the same one. The value can be different if you use them on `"3.14"` but parsing the string `"4.0"` will produce the *exact* same value with either function. – VLAZ Mar 21 '19 at 13:02
  • While that's true of course I assume the OP might want to use decimals since he's using floats in the JSON data, so I can't reccommend using parseInt() for conversion. parseFloat() will handle both cases just fine. – obscure Mar 21 '19 at 13:14