开发者

Comparing negative numbers in javascript

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(n开发者_如何学JAVAum1 < 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?


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜