如何在React中将小数检测为数字

时间:2018-11-19 15:51:29

标签: javascript reactjs

我具有要检测的此函数是value是否为整数。现在,当我输入十进制数字时,我在为数字设置的验证中会出错,我该如何放置 5.79 之类的值。它仅适用于整数

这是检查整数的功能

      static isInt(value: any) {
        var x: any;

       return typeof value =="number";
    }

我使用此验证来检查输入值是否为数字

static checkNumber(value: number, minNumber: number, maxNumber: number): IValdationResuslt {
        if (value >= minNumber) {
            if (value <= maxNumber) {
                return { state: true, message: `Valid` } as Valid;
            }
            return { state: false, message: `Max Characters ${maxNumber} : Entered ${value}` } as IValdationResuslt;
        }
        return { state: false, message: `Min Number ${minNumber} : Entered ${value}` } as Invalid;
    }

这是数字的输入验证检查

static inputValidation(value: any, state: any) {
  switch (state.type) {
    case "number":
      //check if the value is a valid number
      if (this.isInt(value)) {
        //check if the minNumber value hase been exceeded
        return this.checkNumber(value, state.minNumber, state.maxNumber);
      }
      return {
        state: false,
        message: "The value entered is not a number"
      }
      as IValdationResuslt;
    case "telephone":
      //check if the max length value has been exceeded
      if (this.isInt(value)) {
        //check if the minNumber value hase been exceeded
        return this.checkNumber(value, state.minNumber, state.maxNumber);
      }
  }
}

3 个答案:

答案 0 :(得分:2)

您可以使用Number.isFinite()来评估输入是否为数字

const isNumber = (number) => Number.isFinite(number);

let num = 4;
console.log(`${num} is a number: ${isNumber(num)}`);
num = 4.54;
console.log(`${num} is a number: ${isNumber(num)}`);
num = 'a';
console.log(`${num} is a number: ${isNumber(num)}`);

// 4 is a number: true
// 4.54 is a number: true
// a is a number: false

答案 1 :(得分:1)

javascript的Number对象中已经有一个名为isInteger的函数。 如果要检查值是否是数字而不是整数,则只需检查以下内容即可:

!Number.isInteger(value) && typeof value == "number"

答案 2 :(得分:0)

当我将其解析为float时,错误消失了。尽管我将其设置为数字形式,但仍被视为字符串。这样可以节省情况。

static isInt(value: any) 
{       
       var check = parseFloat(value)       
       console.log(typeof check)  

       return check

}