在javascript中比较两个数字的问题

时间:2012-02-01 10:30:59

标签: javascript html

我的HTML代码如下:

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

当我比较这两个值时,使用low是12而high是112则不起作用。 像22和122,33和133等......

我使用的是IE浏览器版本8.请帮助。

6 个答案:

答案 0 :(得分:19)

尝试这样: -

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

或您可以使用的浮动号码

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

或只是使用

Number()

答案 1 :(得分:7)

您需要将它们转换为数字:

if(+l > +h){

一元加号运算符会将字符串值转换为数值。有关详细信息,请参阅此问题:
What's the significant use of unary plus and minus operators?

Live example

答案 2 :(得分:6)

使用parseInt 与基础 获得正确的结果:

var l = parseInt(document.test.low.value, 10);
var h = parseInt(document.test.high.value, 10);

答案 3 :(得分:2)

var lnum = new Number(l);
var hnmu = new Number(h);
if(lnum > hnum){
alert('if');

}else{
alert('else');
}

答案 4 :(得分:0)

比较if语句中的两个字符串时:

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

它将这两个值作为字符串"3" > "1"进行比较。它说l > h true

答案 5 :(得分:0)

您的脚本放在错误的位置。在完成工作后,您的代码可以正常工作

http://jsbin.com/okexuj

<html>
    <body>
        <form name="test">
            <input type="text" size="11" id="low" value="1" />
            <input type="text" size="11" id="high" value="10" />
            <input type="button" value="sss" onclick="pepe(); " />
        </form>

        <script type="text/javascript">
            function pepe() {
              var l = document.test.low.value;
              var h = document.test.high.value;
              //alert("hi " + h + " lo " + l);
              if (l > h) {
                alert("low greater than high low is -"+l+", high is -"+h);
              } else {
                alert("ok, i'll allow it");
              }
            }
        </script>   
    </body>
</html>
相关问题