I have the following code to divide a variable by 100 and power it.
JavaScript
x
4
1
var a = 1;
2
3
var b = (a / 100) ^ 2;
4
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()
:
JavaScript
1
2
1
var b = Math.pow(a / 100, 2);
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:
JavaScript
1
3
1
00000000 XOR 00000010 (0 ^ 2)
2
00000010 (2)
3