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.

5 Answers 5

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)){ /* … */ }
Sign up to request clarification or add additional context in comments.

3 Comments

It will not work if number happens to be octal format: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
yes you are right then in that case:use base value or simply use Number()
idk what the reason is but the Number() did not worked for me , but other stuff works
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.

Comments

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);

2 Comments

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.
@ShadowWizard: In that case + can be prefixed and then parseInt but using + alone won't avoid octal number problem AFAIK.
1
var lnum = new Number(l);
var hnmu = new Number(h);
if(lnum > hnum){
alert('if');

}else{
alert('else');
}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.