Home > other >  Check if a given string is a exponential and then check if it is a whole number?
Check if a given string is a exponential and then check if it is a whole number?

Time:08-16

I am using tkinter to build an application. I have a entry box which when i get the value it returns a string.

where, n_term= entry variable

I can check if it is a integer or not, by using: 'try: str.isdigit(n_term)...',

is there a similar function to check if when user enters a exponential in a string form, eg. "2e5", it checks if it is a whole number.

Test data: "2e5", "2.222e2"

where: "2e5" = true as 2e5 == 2x10^5 == 200000, a integer
"2.222e2" = false as 2.222e2 == 2.222x10^2 == 222.2, a float

CodePudding user response:

You can use this:

def is_whole(n):
    try:
        return float(n) == int(float(n))
    except ValueError:
        return False

Exponential strings can be converted to float. You can then check if that float value is the same as its int value. The except is there in case the user enters an invalid input.

CodePudding user response:

You can use Python's float.is_integer function to check if a float is a whole number.

Return True if the float instance is finite with integral value, and False otherwise:

To check if string s is an integer:

float(s).is_integer()    # Is True/False based upon float being a whole number

Examples:

print(float("2e5").is_integer())       # Output: True
print(float("2.222e2").is_integer())   # Output: False
print(float("-2.222e5").is_integer())  # Output: True
print(float("-2.222e2").is_integer())  # Output: False
  • Related