Skip to content
Advertisement

Division and Power in Javascript

I have the following code to divide a variable by 100 and power it.

  var a = 1;

  var b = (a / 100) ^ 2;

The value in ‘b’ becomes 2 when it should be 0.01 ^ 2 = 0.0001.

Why is that?

Advertisement

Answer

^ is not the exponent operator. It’s the bitwise XOR operator. To apply a power to a number, use Math.pow():

var b = Math.pow(a / 100, 2);

As to why you get 2 as the result when you use ^, bitwise operators compare the individual bits of two numbers to produce a result. This first involves converting both operands to integers by removing the fractional part. Converting 0.01 to an integer produces 0, so you get:

00000000 XOR 00000010   (0 ^ 2)
00000010                (2)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement