18

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.

Sudhakar S
  • 285
  • 1
  • 4
  • 16

5 Answers5

30

try 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()
Pranav
  • 7,315
  • 4
  • 23
  • 40
  • It will not work if number happens to be octal format: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt – Sarfraz Feb 01 '12 at 10:54
  • yes you are right then in that case:use base value or simply use Number() – Pranav Feb 01 '12 at 11:11
  • idk what the reason is but the Number() did not worked for me , but other stuff works – menaka Nov 04 '16 at 07:20
10

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.

Community
  • 1
  • 1
Shadow The Vaccinated Wizard
  • 62,584
  • 26
  • 129
  • 194
6

Use parseInt with base to get correct results:

var l = parseInt(document.test.low.value, 10);
var h = parseInt(document.test.high.value, 10);
Sarfraz
  • 355,543
  • 70
  • 511
  • 562
  • Not sure `parseInt` is good here, for example `10a` will be converted to `10` even though it's not really a number - using the unary plus will make it `NaN` value which is more proper IMO. – Shadow The Vaccinated Wizard Feb 01 '12 at 10:37
  • @ShadowWizard: In that case `+` can be prefixed and then `parseInt` but using `+` alone won't avoid octal number problem AFAIK. – Sarfraz Feb 01 '12 at 10:39
2
var lnum = new Number(l);
var hnmu = new Number(h);
if(lnum > hnum){
alert('if');

}else{
alert('else');
}
Lokesh
  • 23
  • 3
0

When you compare two strings in an if statement:

if ( l > h) {}    
when l = "12" and h = "112"

It compares these two values as strings as "3" > "1". It says l > h is true

Pavel Vladov
  • 4,191
  • 2
  • 31
  • 38
vireshas
  • 786
  • 5
  • 19