How to Check if a Number is Float or Integer in JavaScript?

Like other programming languages, there is no concept of float numbers in JavaScript. It just has one data type Number for all positive, negative integers, and decimal numbers.

Let me just show you the type of a float and integer using the typeof operator:

console.log(typeof(10));
// Output: number

console.log(typeof(10.25));
// Output: number

From the above example, it is clear that the typeof operator always returns 'number' for all integers and decimal values. Therefore, we can’t directly use it to check if the number is float or not.

Well, there is a very helpful method Number.isInteger() which lets you know whether the passed value is an integer or not.

The Number.isInteger() method returns true if the passed number is an integer otherwise it returns false. We can use this method in combination with the typeof operator and isNaN() method to check if the given number is float or integer.

Here is the implementation:

// JavaScript program to check if given number is float or integer

function checkType(val){
    
    // First check if given val is a valid number
    if(typeof(val)==='number' && !isNaN(val)){
        
        // Check if val is an integer
        if(Number.isInteger(val)){
            console.log(`${val} is a an integer.`);   
        }
        else{
            console.log(`${val} is a float.`);
        }
    }
    else{
        console.log(`${val} is not a valid number.`);
    }
    
}

checkType(10);     // 10 is a an integer.
checkType(10.25);  // 10.25 is a float.
checkType(0.54);   // 0.54 is a float.
checkType('10ab'); // 10ab is not a valid number.

Second Approach – Using Remainder(%) operator

You can also use the remainder(%) operator to check if the given number is an integer or float.

You have to just check if number%1 is equals to 0 or not. If it equals to 0, the given number is an integer, otherwise, it’s a float number.

Below is the implementation of this approach:

// JavaScript program to check if given number is float or integer

function checkType(val){
    
    // First check if given val is a valid number
    if(typeof(val)==='number' && !isNaN(val)){
        
        // Check if val is an integer
        if(val%1===0){
            console.log(`${val} is a an integer.`);   
        }
        else{
            console.log(`${val} is a float.`);
        }
    }
    else{
        console.log(`${val} is not a valid number.`);
    }
}

checkType(10);     // 10 is a an integer.
checkType(10.25);  // 10.25 is a float.
checkType(0.54);   // 0.54 is a float.
checkType('10ab'); // 10ab is not a valid number.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.