Checking to see if a string is an integer or float

user6470150 picture user6470150 · Oct 9, 2017 · Viewed 33.4k times · Source

So I'm creating a program to show number systems, however I've run into issues at the first hurdle. The program will take a number from the user and then use that number throughout the program in order to explain several computer science concepts.

When explaining my first section, number systems, the program will say what type of number it is. I'm doing this by converting the string into a float number. If the float number only has '.0' after it then it converts it into a integer.

Currently I'm using this code

while CorrectNumber == False:
try:
    Number = float(NumberString) - 0
    print (Number)
except:
    print ("Error! Not a number!")

This is useful as it shows if the user has entered a number or not. However I am unsure how to now check the value after the decimal place to check if I should convert it into a integer or not. Any tips?

Answer

francisco sollima picture francisco sollima · Oct 9, 2017

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)