Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check that a number is float or integer?

How to find that a number is float or integer?

1.25 --> float   1 --> integer   0 --> integer   0.25 --> float 
like image 491
coure2011 Avatar asked Oct 07 '10 20:10

coure2011


People also ask

How do you see if a number is an integer?

An integer (pronounced IN-tuh-jer) is a whole number (not a fractional number) that can be positive, negative, or zero. Examples of integers are: -5, 1, 5, 8, 97, and 3,043. Examples of numbers that are not integers are: -1.43, 1 3/4, 3.14, .

What is a float vs integer?

An integer is a whole number and a floating-point value, or float, is a number that has a decimal place.

How do you check if a number is a float or integer in Python?

Check if float is integer: is_integer() float has is_integer() method that returns True if the value is an integer, and False otherwise. For example, a function that returns True for an integer number ( int or integer float ) can be defined as follows. This function returns False for str .


2 Answers

check for a remainder when dividing by 1:

function isInt(n) {    return n % 1 === 0; } 

If you don't know that the argument is a number you need two tests:

function isInt(n){     return Number(n) === n && n % 1 === 0; }  function isFloat(n){     return Number(n) === n && n % 1 !== 0; } 

Update 2019 5 years after this answer was written, a solution was standardized in ECMA Script 2015. That solution is covered in this answer.

like image 165
kennebec Avatar answered Oct 06 '22 03:10

kennebec


Try these functions to test whether 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(n) {     return n === +n && n !== (n|0); }  function isInteger(n) {     return n === +n && n === (n|0); } 
like image 21
Dagg Nabbit Avatar answered Oct 06 '22 05:10

Dagg Nabbit