issue with comparing two numbers in javascript

前端 未结 5 1993
滥情空心
滥情空心 2020-11-29 11:29

my html code is like:




        
相关标签:
5条回答
  • 2020-11-29 11:32

    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

    0 讨论(0)
  • 2020-11-29 11:39

    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.

    0 讨论(0)
  • 2020-11-29 11:49

    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()
    
    0 讨论(0)
  • 2020-11-29 11:53

    Use parseInt with base to get correct results:

    var l = parseInt(document.test.low.value, 10);
    var h = parseInt(document.test.high.value, 10);
    
    0 讨论(0)
  • 2020-11-29 11:55
    var lnum = new Number(l);
    var hnmu = new Number(h);
    if(lnum > hnum){
    alert('if');
    
    }else{
    alert('else');
    }
    
    0 讨论(0)
提交回复
热议问题