Skip to content
Advertisement

Division and Power in Javascript

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

JavaScript

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

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
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement