[Solved-6 Solutions] How do we check that a number is float or integer - javascript tutorial



Problem:

How to find that a number is float or integer ?

Solution 1:

If you want Simply solve this problem by using a simple regular expression.

function isInt_number(v) {

	var num = /^-?[0-9]+$/;
 
	return er.test(value);
}


function isFloat_number(v) {
	var num = /^[-+]?[0-9]+\.[0-9]+$/;
	return num.test(v);
}

Solution 2:

Check the modules of a number when its dividing by 1:

function isInt_number(num) {
   return num % 1 === 0;
}

The above solution doesn't give the clear idea about the argument is number or not then we use two methods to find if the number is integer or float.

function isInt_number(num){
    return Number(num) === num && num % 1 === 0;
}

function isFloat_number(num){
    return Number(num) === num && num % 1 !== 0;
}

Solution 3:

The above solution will also return true for an empty string. Try an alter function to avoid those confusion whether test a value is a number primitive value that has no fractional part and is within the size limits of what can be represented as an exact integer.

function isFloat_number(num) {
    return num === +num && num!== (num|0);
}

function isInt_number(num) {
    return num === +num && num === (num|0);
}

Solution 4:

The better way to solve the problem is

var isInt_number = function(num) { return parseInt(num) === num };

Solution 5:

We also use Number.isInteger() method which is currently implemented in latest Firefox. But still is a part of EcmaScript 6 proposal however MDN provides a polyfill for the other browsers to match the specified one in ECMA harmony:

if (!Number.isInteger) {
  Number.isInteger = function isInt_number (num_value) {
    return typeof num_value === "number" && isFinite(num_value) && num_value > -9007199254740992 && num_value < 9007199254740992 && Math.floor(num_value) === num_value;
  };
}

Solution 6:

There is a efficient functions that check if the value is a number or not. It define a value is not a number then the value can be safely converted to a number:

function isNum(v) {
    if ((undefined === v) || (null === v)) {
        return false;
    }
    if (typeof v == 'num') {
        return true;
    }
    return !isNaN(v - 0);
}

This solution return false when a value is float that why we use another evaluated method:

function isInteger(value) {
    if ((undefined === value) || (null === value)) {
        return false;
    }
    return value % 1 == 0;
}
  • The parseInt (or parseNumber) are avoided when the value already is a number.
  • Because the parsing functions always convert to string first and then attempt to parse that string, which would be a waste if the value already is a number.



Related Searches to javascript tutorial - How do we check that a number is float or integer ?