I need to find if a number is a float or an integer in an if condition
and I'm having trouble doing so in Python. Will I need to use the is_integer()
method and if so how?
Asked
Active
Viewed 43 times
0
-
Use *isinstance()* – DarkKnight Sep 23 '22 at 15:14
-
Do you mean is the variable of type `int` or `float`, or does the float (approximately) equal an integer value? – sj95126 Sep 23 '22 at 15:14
-
Does this answer your question? [Check if a number is int or float](https://stackoverflow.com/questions/4541155/check-if-a-number-is-int-or-float) – JNevill Sep 23 '22 at 15:14
-
Does this answer your question? [What's the canonical way to check for type in Python?](https://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python) – Thomas Sep 23 '22 at 15:14
-
@Cdr Is there any code you are trying with? – Eftal Gezer Sep 23 '22 at 15:16
2 Answers
2
You can write your code like this:
value = 1.5
if type(value) == float:
print("it is float")

Mohammed almalki
- 76
- 8
0
isinstance
is a built in method for this purpose.
my_var = 5.5 # float
if isinstance(my_var, float):
print(f'{my_var} is a float')
elif isinstance(my_var, int):
print(f'{my_var} is an integer')

alvrm
- 311
- 2
- 9