Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(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?

like image 876
Tom G Avatar asked Aug 09 '10 17:08

Tom G


People also ask

How do you compare negative numbers in JavaScript?

To check if a value is a negative number, compare it to 0 , e.g. num < 0 . If the value to the left hand side of the less-than operator is not already a number, it will get converted to one and compared to 0 . If the expression returns true , the value is a negative number.

How do you compare negative numbers?

Introduction. How are negative numbers compared? On a number line, numbers always increase (become "more positive") to the right and decrease (become "more negative") to the left. Numbers to the right are greater than numbers to the left and numbers to the left are less than numbers to the right.

How do you check if a number is negative in JavaScript?

The Math. sign() is a built-in function in JavaScript and is used to know the sign of a number, indicating whether the number specified is negative or positive.


1 Answers

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

like image 121
Seth Avatar answered Oct 12 '22 16:10

Seth