Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

issue with comparing two numbers in javascript

my html code is like:

<html>
<SCRIPT type="text/javascript" language="JavaScript">   
function fun()
{
var l = document.test.low.value;
var h = document.test.high.value;
alert(l);
alert(h);
    if(l >h){
        alert("low greater than high low is -"+l+"high is -"+h);
    }
}
</SCRIPT>

<body>

<form name="test">
<input type="text" size="11" id="low" />
<input type="text" size="11" id="high" />
<input type="button" value="sss" onClick="fun()"/> 
</form>
</body>
</html>

when i compare this two values using low is 12 and high is 112 is not working. like 22 and 122, 33 and 133 etc....

I am using IE browser version 8. please help.

like image 227
Sudhakar S Avatar asked Feb 01 '12 10:02

Sudhakar S


2 Answers

Try it like this:

if (parseInt(l,10) > parseInt(h,10))

or for floating numbers you can use

if (parseFloat(l,10) > parseFloat(h,10))

or simply use

Number()
like image 188
Pranav Avatar answered Oct 08 '22 21:10

Pranav


You need to convert them to numbers:

if(+l > +h){

The unary plus operator will convert the string value to numeric value. See this question for more details:
What's the significant use of unary plus and minus operators?

Live example.

like image 30
Shadow Wizard Hates Omicron Avatar answered Oct 08 '22 20:10

Shadow Wizard Hates Omicron