Miguel Moura
Miguel Moura

Reputation: 39464

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?

Upvotes: 0

Views: 521

Answers (4)

Topicus
Topicus

Reputation: 1404

Update 2021:

Exponentiation operator is available since ECMAScript 2016.

So, you can do something like:

var b = (a / 100) ** 2;

Upvotes: 0

mico
mico

Reputation: 12748

Power in javasript is made with Math.pow(x, y) function, not typing ˆ in between.

http://www.w3schools.com/jsref/jsref_pow.asp

Upvotes: 0

thriqon
thriqon

Reputation: 2488

Try this:

2 ^ 10

It gives you 8. This is easily explained: JS does not have a power operator, but a XOR: MDN.

You are looking for Math.pow (MDN)

Upvotes: 1

JLRishe
JLRishe

Reputation: 101730

^ 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)

Upvotes: 6

Related Questions