Why javascript accepts decimal as integer

I have this html:

<input type='number' id='length' step='0.1' min='0'; max='5'>Length

and this javascript

num=document.getElementById('length').value;
if(num==1 || 2 || 3 || 4|| 5){
num='0'+num;
}

My problem is this: while I want the code inside the brackets to be executed if the number from the input is an integer, it is also activated if it detects 0.8 or some other decimal number. Any idea why? How to fix it? Thank.

+4
source share
4 answers

To make sure that numis an integer, without having to determine all the possibilities, use:

if (num % 1 == 0)
+7
source

Why:

num==1 || 2 || 3 || 4|| 5

equally:

(num==1) || 2 || 3 || 4|| 5

, num "1" ( ), true, 2 ( ), if .

:

// implicitly converts the string type into number type before comparison
// returns true if it is an integer-like string
num == Math.floor(num) 

, :

if (num == Math.floor(num) && num > 0 && num < 6) {
    // an integer-like string that meets the requirement [1, 5]
}

, num string. number, :

num = +num
+3

You have to do

if (num == 1 || num == 2 || num == 3 || num == 4 || num == 5)

WRONG - otherwise, it will compare 2 to 2 and says that this is true for the last 4 “if” parameters.

CORRECTO - any number in JS is considered true.

+2
source

You need to edit the "If" loop:

if (num == 1 || num == 2 || num == 3 || num == 4 || num == 5)
+1
source

Source: https://habr.com/ru/post/1599693/


All Articles