How to find that a number is float or integer ?
If you want Simply solve this problem by using a simple regular expression.
Check the modules of a number when its dividing by 1:
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.
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.
Read AlsoTo check if a string is a valid number
The better way to solve the problem is
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:
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:
This solution return false when a value is float that why we use another evaluated method:
- 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.