Check If a Number Is Int or Float

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 returnfalse 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 floats.

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

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.

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.

Checking to see if a string is an integer or float

If the string is convertable to integer, it should be digits only. It should be noted that this approach, as @cwallenpoole said, does NOT work with negative inputs beacuse of the '-' character. You could do:

if NumberString.isdigit():
Number = int(NumberString)
else:
Number = float(NumberString)

If you already have Number confirmed as a float, you can always use is_integer (works with negatives):

if Number.is_integer():
Number = int(Number)

How to check if input is float or int?

TLDR: Convert your input using ast.literal_eval first.


The return type of input in Python3 is always str. Checking it against type(2.2) (aka float) and type(2) (aka int) thus cannot succeed.

>>> number = input()
3
>>> number, type(number)
('3', <class 'str'>)

The simplest approach is to explicitly ask Python to convert your input. ast.literal_eval allows for save conversion to Python's basic data types. It automatically parses int and float literals to the correct type.

>>> import ast
>>> number = ast.literal_eval(input())
3
>>> number, type(number)
(3, <class 'int'>)

In your original code, apply ast.literal_eval to the user input. Then your type checks can succeed:

import ast

number = ast.literal_eval(input("Please input your number...... \n"))
if type(number) is float:
print("Entered number is float and it's hexadecimal number is:", float.hex(number))
elif type(number) is int:
print("Entered number is, ", number,"and it's hexadecimal number is:", hex(number))
else:
print("you entered an invalid type")

Eagerly attempting to convert the input also means that your program might receive input that is not valid, as far as the converter is concerned. In this case, instead of getting some value of another type, an exception will be raised. Use try-except to respond to this case:

import ast

try:
number = ast.literal_eval(input("Please input your number...... \n"))
except Exception as err:
print("Your input cannot be parsed:", err)
else:
if type(number) is float:
print("Entered number is float and it's hexadecimal number is:", float.hex(number))
elif type(number) is int:
print("Entered number is, ", number, "and it's hexadecimal number is:", hex(number))
else:
print("you entered an invalid type")

How to check whether input value is integer or float?

You should check that fractional part of the number is 0.
Use

x==Math.ceil(x)

or

x==Math.round(x)

or something like that

How do I check if a string represents a number (float or int)?

Which, not only is ugly and slow

I'd dispute both.

A regex or other string parsing method would be uglier and slower.

I'm not sure that anything much could be faster than the above. It calls the function and returns. Try/Catch doesn't introduce much overhead because the most common exception is caught without an extensive search of stack frames.

The issue is that any numeric conversion function has two kinds of results

  • A number, if the number is valid
  • A status code (e.g., via errno) or exception to show that no valid number could be parsed.

C (as an example) hacks around this a number of ways. Python lays it out clearly and explicitly.

I think your code for doing this is perfect.



Related Topics



Leave a reply



Submit