How to judge the size of two numbers with JS

  • 2021-07-04 18:04:36
  • OfStack

Foreword:

Before judging, we should first know that the variables defined by var in js are strings by default. If we simply compare strings, there will be errors, which need to be converted to int type for comparison.

"Note: 110 and 18 are 18 in the program you write, because these two numbers are strings, and after 1 and 1 are equal, compare 1 and 8, of course 8 is big, so 18 is big. You convert to INT before comparing. if (parseInt (num2) > parseInt (num1)) "

Error instance:


<script> 
 function check() 
 { 
 var num1=document.form1.num1.value; 
 var num2=document.form1.num2.value; 
 if(num2>num1) <!- Wrong writing -->
 { 
 alert('num2 > num1 ! '); 
 return false; 
 } 
 return true; 
 } 
 </script> 

Correct example:


<script> 
 function check() 
 { 
 var num1=document.form1.num1.value; 
 var num2=document.form1.num2.value; 
 if(parseInt(num2)>parseInt(num1)) <!- Correct writing (converted to INT ) -->
 { 
 alert('num2 > num1 ! '); 
 return false; 
 } 
 return true; 
 } 
 </script> 

The above two examples of right and wrong demonstrate how to judge the size of two numbers, so don't get confused.


Related articles: