jQuery 检查正数或负数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1081742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:37:21  来源:igfitidea点击:

Checking for positive or negative number

jquerylivevalidation

提问by Nazmul Hasan

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

我们如何在 LiveValidation 中检查输入数字是正数还是负数?

回答by TheVillageIdiot

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

更简单的方法是将内容乘以 1,然后将 +ve 或 -ve 与 0 进行比较

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

回答by Artem Barger

try
{
    if ((new Number( $('#numberInput').val()) < 0)
    {
        // Number is negative
    }
    else
    {
        // Otherwise positive
    }
} catch ( error)
{
    alert( "Not a number!");
}

回答by Dev

You can also use JavaScript's method eg:

您还可以使用 JavaScript 的方法,例如:

var pos_value = Math.abs(n_val);

Thanks Dev

感谢开发