-1

This is something that I have not been able to resolve.

The issue is that I am looking for an integer as an output.

I have written some sample code, which is:

tempVal1 = 4+5 print ("The value is of tempval1 integer: ", tempVal1, "\n and it is an integer ",isinstance(tempVal1, int)) tempVal2 = math.sqrt(36) print ("The value is of tempval2 integer: ", tempVal2, "\n and it is an integer ", isinstance(tempVal2, int)) 

The output is

from what I can see, the ouput of the square root is coming as a float.

I have looked at operator.index(tempVal2) and it sets everything as integer values.

The output that i am looking is to checkj if the number is an integer or not.

Can anyone advise me what steps to take?

If it was C# for example, I would try something like

if(int.TryParse(inputString, out val)) 
4
  • 4
    Does this answer your question? How to check if a float value is a whole number Commented Apr 12, 2024 at 14:24
  • From Python 3.12 forward, x.is_integer(). Commented Apr 12, 2024 at 14:31
  • Hi Elerium, thanks that has resolved it, could you put it in a post and I will give you credit for it Commented Apr 12, 2024 at 14:32
  • @user3569147 you can give credit to the answer in the linked question if it solved your problem. Commented Apr 12, 2024 at 15:19

2 Answers 2

2

From Python 3.12 forward, you can use the aptly named .is_integer() method on both floats and ints.

On earlier versions, that method only existed on floats.

Sign up to request clarification or add additional context in comments.

1 Comment

Since it only existed on floats prior to 3.12, you might also do float(n).is_integer()
0

So, you write a function called is_whole_number which checks if the modulo of the value is zero.

def is_whole_number(num): return isinstance(num, (int, float)) and num % 1 == 0 print(is_whole_number(5.0)) print(is_whole_number(5.5)) 

Hope this helps.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.