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
  • 385
  • 1
  • 4
  • 16

5 Answers5

32

Convert the values to numbers:

if(Number(l) > Number(h)){ /* … */ }

or alternatively, parse each string as a float:

if(Number.parseFloat(l) > Number.parseFloat(h)){ /* … */ }

or as an integer:

if(Number.parseInt(l, 10) > Number.parseInt(h, 10)){ /* … */ }
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Pranav
  • 8,563
  • 4
  • 26
  • 42
  • 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
11

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 GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
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
  • 377,238
  • 77
  • 533
  • 578
  • 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 GPT 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
1
var lnum = new Number(l);
var hnmu = new Number(h);
if(lnum > hnum){
alert('if');

}else{
alert('else');
}
Lokesh
  • 21
  • 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,707
  • 3
  • 35
  • 39
vireshas
  • 806
  • 6
  • 19