﻿ Check If the Number Is Integer - ITCodar

# Check If the Number Is Integer

## How can I check if a value is of type Integer?

If input value can be in numeric form other than integer , check by

``if (x == (int)x){   // Number is integer}``

If string value is being passed , use `Integer.parseInt(string_var).`
Please ensure error handling using try catch in case conversion fails.

## How to check if a variable is an integer in JavaScript?

Use the === operator (strict equality) as below,

``if (data === parseInt(data, 10))    alert("data is integer")else    alert("data is not an integer")``

## Checking if a number is an Integer in Java

Quick and dirty...

``if (x == (int)x){   ...}``

edit: This is assuming x is already in some other numeric form. If you're dealing with strings, look into `Integer.parseInt`.

## Check if the number is integer

Another alternative is to check the fractional part:

``x%%1==0``

or, if you want to check within a certain tolerance:

``min(abs(c(x%%1, x%%1-1))) < tol``

## Checking whether a variable is an integer or not

If you need to do this, do

``isinstance(<var>, int)``

unless you are in Python 2.x in which case you want

``isinstance(<var>, (int, long))``

Do not use `type`. It is almost never the right answer in Python, since it blocks all the flexibility of polymorphism. For instance, if you subclass `int`, your new class should register as an `int`, which `type` will not do:

``class Spam(int): passx = Spam(0)type(x) == int # Falseisinstance(x, int) # True``

This adheres to Python's strong polymorphism: you should allow any object that behaves like an `int`, instead of mandating that it be one.

### BUT

The classical Python mentality, though, is that it's easier to ask forgiveness than permission. In other words, don't check whether `x` is an integer; assume that it is and catch the exception results if it isn't:

``try:    x += 1except TypeError:    ...``

This mentality is slowly being overtaken by the use of abstract base classes, which let you register exactly what properties your object should have (adding? multiplying? doubling?) by making it inherit from a specially-constructed class. That would be the best solution, since it will permit exactly those objects with the necessary and sufficient attributes, but you will have to read the docs on how to use it.

## How to check if number is integer number, with good precision?

You can check if a given number is a square of an integer using the code below:

``def is_square(x):    s = int(sqrt(x) + 0.5)    return s * s == x``

Similar approach can be used for a diophantine equation. Just convert y found for a given x to int (y = int(y + 0.5)) and then check if diophantine equation is true for found given x and y

## Dart/Flutter check if value is an integer/whole number

Dart numbers (the type `num`) are either integers (type `int`) or doubles (type `double`).

It is easy to check if a number is an `int`, just do `value is int`.

The slightly harder task is to check whether a `double` value has an integer value, or no fractional part. There is no simple function answering that, but you can do `value == value.roundToDouble()`. This removes any fractional part from the `double` value and compares it to the original value. If they are the same, then there was no fractional part.

So, a helper function could be:

``bool isInteger(num value) =>     value is int || value == value.roundToDouble();``

I use `roundToDouble()` instead of just `round()` because the latter would also convert the value to an integer, which may give a different value for large double values.

## Checking if float is an integer

Apart from the fine answers already given, you can also use `ceilf(f) == f` or `floorf(f) == f`. Both expressions return `true` if `f` is an integer. They also return`false` for NaNs (NaNs always compare unequal) and `true` for ±infinity, and don't have the problem with overflowing the integer type used to hold the truncated result, because `floorf()`/`ceilf()` return `float`s.

## Check if float is an integer: is_integer() vs. modulo 1

All are valid for the purpose. The `math.floor` option requires exact matching between a specific value and the result of the floor function. Which is not very convenient if you want to encapsulate it in a generic method. So it boils down to the first and third option. Both are valid and will do the job. So the key difference is simple - performance:

``from timeit import Timerdef with_isint(num):    return num.is_integer()def with_mod(num):    return num % 1 == 0Timer(lambda: with_isint(10.0)).timeit(number=10000000)#output: 2.0617980659008026Timer(lambda: with_mod(10.0)).timeit(number=10000000)#output: 2.6560597440693527``

Naturally this is a simple operation so you'd need a lot of calls in order to see a considerable difference, as you can see in the example.

## C - How to check if the number is integer or float?

I would suggest the following:

1. Read the number into a floating point variable, `val`, say.
2. Put the integer part of `val` into an int variable, `truncated`, say.
3. Check whether or not `val` and `truncated` are equal.

The function might look like this:

``bool isInteger(double val){    int truncated = (int)val;    return (val == truncated);}``

You will likely want to add some sanity checking in case `val` is outside the range of values that can be stored in an `int`.

Note that I am assuming that you want to use a mathematician's definition for an integer. For example, this code would regard `"0.0"` as specifying an integer.