检查字符串是否为整数或浮点数 [英] Checking to see if a string is an integer or float

查看:126
本文介绍了检查字符串是否为整数或浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在创建一个显示数字系统的程序,但是我遇到了第一个障碍.该程序将从用户那里获取一个数字,然后在整个程序中使用该数字,以解释几种计算机科学概念.

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.

在解释我的第一部分,数字系统时,程序将说明它是什么类型的数字.我是通过将字符串转换为浮点数来实现的.如果浮点数后面仅带有".0",则会将其转换为整数.

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.

当前我正在使用此代码

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?

推荐答案

如果字符串可以转换为整数,则只能为数字.应当指出,正如@cwallenpoole所说,这种方法不适用于负输入,因为它是'-'字符.您可以这样做:

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)

如果您已经将数字确认为浮点数,则可以始终使用is_integer(适用于负数):

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)

这篇关于检查字符串是否为整数或浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆