lutakyn
lutakyn

Reputation: 474

How To Detect Decimal as a Number in React

I have this function I am using to detect is value is an integer or not. Now when I put decimal numbers, I throws an error in the validation I set for numbers.How will I put values like 5.79. It works on only integers

This is the function to check for integer

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

       return typeof value =="number";
    }

I used this validation to check if input value is a 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;
    }

This is the input validation check for numbers

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

Upvotes: 2

Views: 4762

Answers (3)

Gilad Bar
Gilad Bar

Reputation: 1322

javascript already has a function called isInteger in it's Number object. If you want to check if the value is a number but not an integer, just check for:

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

Upvotes: 2

lutakyn
lutakyn

Reputation: 474

When I parsed it as a float the error is gone. It was being seen as as string although I set it as a number in the form.This saves the situation.

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

       return check

}

Upvotes: 0

Dinesh Pandiyan
Dinesh Pandiyan

Reputation: 6289

You can use Number.isFinite() to evaluate if an input is number or not

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

Upvotes: 3

Related Questions