13

I'm sure this is a simple problem, but I'm comparing negative numbers in javascript i.e.:

var num1 = -83.778;
var num2 = -83.356;

if(num1 < num2)
{
    // Take action 1
}
else
{
    // Take action 2
}

This script will always take action 2, even though num1 is less than num2. Whats going on here?

8
  • 1
    This works for me. >>> -83.778 < -83.356 -> true. Platform / JS Version / Browser version? Commented Aug 9, 2010 at 17:10
  • 1
    Hi, I tested myself, and it take the action 1. There nothing wrong about the comparing here. Maybe your code is wrong somewhere else Commented Aug 9, 2010 at 17:10
  • Are you sure that's all there is to it? It works for me. Commented Aug 9, 2010 at 17:12
  • no, it is behaving properly with me.can you please check it again Commented Aug 9, 2010 at 17:12
  • 1
    OK, then I must be doing something completely stupid here. Thanks Commented Aug 9, 2010 at 17:19

3 Answers 3

25

How does if (parseFloat(num1) < parseFloat(num2)) work? Maybe your numbers are turning into strings somewhere.

Sign up to request clarification or add additional context in comments.

2 Comments

exactly. I was getting the numbers from a JSON response and not parsing them back into floats. Haha sorry everyone....
Really, JS was comparing two strings with the negative values, thanks for that answer.
0

This case also works when we want to compare signed characters for both positive and negative numbers. For my case i had numbers like +3, +4, 0, -1 etc..

Directly using if(num1 > num2) would compare these values as string and we would get output of string comparision.

Thus to compare signed numbers., compare them via if (parseFloat(num1) < parseFloat(num2))

Comments

0

I have the same issue. Workaround for that:

var num1 = -83.778;
var num2 = -83.356;
if((num1 - num2) < 0)
{
    // Take action 1
}
else
{
    // Take action 2
}

Now Ation 1 will be used.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.