Home > Blockchain >  Does JavaScript do PEMDAS when doing mathematical calculations?
Does JavaScript do PEMDAS when doing mathematical calculations?

Time:11-26

The following line:

console.log(ship.x   "   "   (4/3)   " * "   ship.r   " * "   Math.cos(ship.a));

returns:

50   1.3333333333333333 * 15 * 6.123233995736766e-17

however when I actually do the math with JavaScript via:

console.log(ship.x   4 / 3 * ship.r * Math.cos(ship.a));

it returns the integer value of '50'? How is this possible? The first value in the line is 50 so you would think it would logically be a bigger number once it is ran. I've tried PEMDAS and many other variations and never end up with the value of 50. What exactly is JavaScript doing with the above code? Here's a link to the entire code page: https://codepen.io/hoyos/pen/vYJqaRw?editors=0010

CodePudding user response:

Calculuswhiz's comment is correct. Floating-point math cannot handle the size of your number (6e-17), so you end up with 50 1.33333 * 15 * 0, which is 50 0.

Check out the approved answer to this question for more details: Is floating point math broken?

  • Related