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?
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.
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.
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.
How does if (parseFloat(num1) < parseFloat(num2))
work? Maybe your numbers are turning into strings somewhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With