Checking to see if a string is an integer or float

丶灬走出姿态 提交于 2019-12-01 01:28:00

问题


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?


回答1:


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)



回答2:


Not sure I follow the question but here is an idea:

test = ['1.1', '2.1', '3.0', '4', '5', '6.12']

for number in test:
    try:
        print(int(number))
    except ValueError:
        print(float(number))

Returns:

1.1
2.1
3.0
4
5
6.12



回答3:


This checks if the fractional-part has any non-zero digits.

def is_int(n):
    try:
        float_n = float(n)
        int_n = int(float_n)
    except ValueError:
        return False
    else:
        return float_n == int_n

def is_float(n):
    try:
        float_n = float(n)
    except ValueError:
        return False
    else:
        return True

Testing the functions:

nums = ['12', '12.3', '12.0', '123.002']

for num in nums:
    if is_int(num):
        print(num, 'can be safely converted to an integer.')
    elif is_float(num):
        print(num, 'is a float with non-zero digit(s) in the fractional-part.')

It prints:

12 can be safely converted to an integer.
12.3 is a float with non-zero digit(s) in the fractional-part.
12.0 can be safely converted to an integer.
123.002 is a float with non-zero digit(s) in the fractional-part.



回答4:


Here is the method to check,

a = '10'
if a.isdigit():
   print "Yes it is Integer"
elif a.replace('.','',1).isdigit() and a.count('.') < 2:
   print "Its Float"
else:
   print "Its is Neither Integer Nor Float! Something else"


来源:https://stackoverflow.com/questions/46647744/checking-to-see-if-a-string-is-an-integer-or-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!