srchulo
srchulo

Reputation: 5203

javascript ints evaluating incorrectly

So I am writing a javascript application, and basically if one number is greater than another I want to swap their values:

if(price1 > price2)
{
  var temp = price1;
  price1 = price2;
  price2 = temp;
}

This works fine up until a certain point, but once the numbers starting getting larger, i.e.:

price1: 12345678
price2: 234556

Then the expression will evaluate to false and will do nothing. Does anyone know what the issue is? Thanks!

Upvotes: 2

Views: 100

Answers (3)

Eineki
Eineki

Reputation: 14909

Are you shure you are testing numbers?

As stated the values you specify are not so large to justify an error of that kind. It seems to me that the values are tested in lexicographic (as strings) order.

I would change your code accordingly

if(Number(price1) > Number(price2)) {
    var temp = price1;
    price1 = price2;
    price2 = temp;
}

Upvotes: 1

chuckj
chuckj

Reputation: 29485

Are you sure these are being compared as numbers? For example, if you change the code to

if (+price1 > +price2) {
    var temp = price1;
    price1 = price2;
    price2 = temp;
}

does it work? If so price1 and price2 are strings and the prefix + converts them to numbers.

Upvotes: 4

Frankie
Frankie

Reputation: 25165

I'm assuming both price1 & price2 are ints.

That to be correct they should have a precision of +/- 9007199254740992.

Upvotes: 0

Related Questions