简体   繁体   English

检查值是否为数字做某事

[英]check if value is numeric do something

I'm trying to check if a value passed is either a string or a number with the below script 我正在尝试使用以下脚本检查传递的值是字符串还是数字

$scope.checkval=function(res){
    console.log(res.profile_id)
    if(angular.isNumber(res.profile_id)){
        console.log('Number');
     }else {
        console.log('Center Code is not a number');
     }
}

from the above code i'm always getting Center code is not a number , though the value passed is numeric 从上面的代码中,我总是得到Center code is not a number ,尽管传递的值是数字

That API is not for checking to see if a string is a number; 该API不用于检查字符串是否为数字。 it's checking to see whether the value already is a number. 它正在检查该值是否已经是一个数字。

The simplest thing to do is use the + unary operator to coerce the value to be a number, and then use !isNaN() to verify that it was in fact a parseable numeric string. 最简单的方法是使用+一元运算符将值强制为数字,然后使用!isNaN()验证它实际上是可解析的数字字符串。

$scope.checkval = function(n) {
  return !isNaN(+n);
};

That'll return true when the value can be converted to an actual number. 当值可以转换为实际数字时,它将返回true Note that the constant NaN is also a number, but you probably don't want to include NaN in your definition of "numeric". 请注意,常数NaN也是一个数字,但是您可能不希望在“数字”的定义中包括NaN

isNumber is a pretty accurate function so I personally would believe that the value you are passing is probably a string. isNumber是一个非常准确的函数,因此我个人认为您传递的值可能是字符串。 But in order to avoid that potential issue you can do this, it will eliminate the potential for a string thats a number, but not correct a string that is not. 但是为了避免该潜在问题,您可以执行此操作,这将消除字符串为数字的可能性,但不能纠正不是字符串的可能性。

$scope.checkval = function(res){
    //unary operator will convert the string into a number if appropriate
    var numberToCheck = +res;
    if (angular.isNumber(numberToCheck)) {
        console.log('Number');
     } else {
        console.log('Center Code is not a number');
     }
}

Pointy's solution is a much better way to go about it if you don't want to/can't use the angular built in functions 如果您不想/不能使用内置函数的角度,Pointy的解决方案是更好的解决方案

是像“ 5”或“ 5”那样传递变量。

res.profile_id = 5; //would come out as true

res.profile_id = '5'; //would come out as false

It is likely that res.profile_id is actually a string. res.profile_id可能实际上是一个字符串。

if you are expecting it to be an integer (like if it is a primary key coming back from the DB), you can caste it explicitly to an int by using: 如果期望它是一个整数(例如,如果它是从数据库返回的主键),则可以使用以下命令将其显式转换为int:

res.profile_id = parseInt(res.profile_id, 10);

If this is a user input field or it is likely that there would be text in the response, you can test for it like so: 如果这是用户输入字段,或者响应中可能有文本,则可以像这样测试它:

if (!isNaN(res.profile_id){
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM