John
John

Reputation: 29

Checking if user input is a floating number

choice = input.questionFloat('\t1. Display all members\' information \n\t2. Display member information \n\t3. Add new member \n\t4. Update points earned \n\t5. Statistics\n\t6. Exit \n\t>> ');
if (choice.toString().includes('.')) {
   console.log ('Please enter a valid input.');
}

choice contains the input from the user. If choice is a floating number, it will prompt the user that it is a invalid input. If there a better way of doing this instead of using .includes?

Upvotes: 0

Views: 386

Answers (2)

touri
touri

Reputation: 169

Why not compare it to its value in int?

const intValue = 12
console.log(parseInt(value) !== value) // false => is an int

const floatValue = 12.1
console.log(parseInt(value) !== value) // true => is not an int

Upvotes: 0

owenizedd
owenizedd

Reputation: 1295

You can do that easily with JavaScript.
First take and convert to number and check if it's truthy value (non NaN) and check if it's not integer.

const num = Number('123.3')
if (num && !Number.isInteger(num)){
    //float
}

Upvotes: 2

Related Questions