## Integer check

### Andy (view profile)

on 21 Sep 2011
Latest activity Commented on by Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 16 Sep 2019
Accepted Answer by Sean de Wolski

### Sean de Wolski (view profile)

How can i do an integer check in matlab? Say i have a number, a = 1.5, how do i check if it is integer or not? i want to use an if statement:
if non_integer(a) == true
end
so i need to know what to use for "non_integer", which would return a true or false

on 21 Sep 2011

floor(x)==x

Walter Roberson

### Walter Roberson (view profile)

on 21 Sep 2011
Fails on inf and -inf ;-)
Jukka Kaipala

### Jukka Kaipala (view profile)

on 27 Jul 2016
Like it should. Inf is not considered an integer, and the same goes for NaN.
Thorsten

### Thorsten (view profile)

on 2 Nov 2016
Like it should not. Because Inf is not an integer, but
floor(inf) == inf
returns true.
So the correct test would be
~isinf(x) & floor(x) == x
Or, as Walter suggests,
mod(x,1) == 0
But this may be all just of theoretical interest.

### Walter Roberson (view profile)

on 21 Sep 2011

I suggest you think about floor(), ceil(), fix(), and round()

Walter Roberson

### Walter Roberson (view profile)

on 21 Sep 2011
A test that works even for nan and inf and -inf :
mod(x,1) == 0
Walter Roberson

### Walter Roberson (view profile)

on 2 Nov 2016
NaN == 0 is false, so in each of those cases, the result of the test would be false, indicating that the values are not integers.
But if you tried the one above, floor(inf)==inf then the result would be true, seemingly indicating that it is an integer when it is not.

### Fandi Bataineh (view profile)

on 2 Feb 2019
Edited by Fandi Bataineh

### Fandi Bataineh (view profile)

on 2 Feb 2019

use
floor(x)==ceil(x)
this will be true only for integers

Sivyer Ge

### Sivyer Ge (view profile)

on 24 Feb 2019
Actually this will not work for type 'char'. Do you know other way to identify the difference between char and integer?

### Manuel Alcazar (view profile)

on 16 Sep 2019

function [bool,idx] = isint(x)
% Check whether input is integer or not
% Inf and NaN are not integers
if ~isnumeric(x)
error('Input must be a numeric, not a %s.',class(x))
end
bool = (mod(x,1) == 0);
% bool = (round(x) == floor(x)); % Other approach. Fails with Inf and
% NaN.
idx = find(bool);
% Manolín Sept-2019
end

### per isakson (view profile)

on 16 Sep 2019

function isf = isflint( m )
% floating double only
%
assert( isa( m, 'double' ) && isvector( m ) ...
, 'isflint:IllegalInput' ...
, 'The input should be a double vector' )
isf = all( abs( m ) <= flintmax ) ...
&& all( floor( m ) == m ) ;
end

#### 1 Comment

Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 16 Sep 2019
This could be trivially vectorized: why force it to return a scalar?