Checking a positive or negative number

How can we check if the input number is positive or negative in LiveValidation?

+3
source share
3 answers

the easiest way is to multiply the contents by 1 and then compare with 0 for + ve or -ve

try{
   var n=$("#...").val() * 1;
   if(n>=0){
        //...Do stuff for +ve num
   }else{
       ///...Do stuff -ve num
   }       
}catch(e){
  //......
}

REGEX:

 var n=$("#...").val()*1;
 if (n.match(new RegExp(^\d*\.{0,1}\d*$))) {
   // +ve numbers (with decimal point like 2.3)
 } else if(n.match(new RegExp(^-\d*\.{0,1}\d*$))){
   // -ve numbers (with decimal point like -5.34)
 }
+4
source
try
{
    if ((new Number( $('#numberInput').val()) < 0)
    {
        // Number is negative
    }
    else
    {
        // Otherwise positive
    }
} catch ( error)
{
    alert( "Not a number!");
}
+3
source

You can also use the JavaScript method, for example:

var pos_value = Math.abs(n_val);

Thanks Dev

-1
source

Source: https://habr.com/ru/post/1711842/


All Articles