How to check whether a floating-point variable is an integer (has no fractional part) in Python

4 Answers

0 votes
import math

d = 24278.0

if d == math.floor(d):
    print("The double variable contains an integer")
else:
    print("The double variable contains a floating point")



'''
run:

The double variable contains an integer

'''

 



answered Jun 7, 2024 by avibootz
0 votes
x = 37298.0

if x.is_integer():
    print("Integer")
else:
    print("Float")
 
 
 
'''
run:
 
Integer
 
'''

 



answered Sep 10 by avibootz
0 votes
x = 37298.0

if x % 1 == 0:
    print("Integer")
else:
    print("Float")
 
 
 
'''
run:
 
Integer
 
'''

 



answered Sep 10 by avibootz
0 votes
# ---------------------------------------------------------------------------
# Demonstrates how to check whether a floating‑point value (Python float)
# represents an integer. Python's float behaves like a double in many languages.
# ---------------------------------------------------------------------------

def is_integer(value: float) -> bool:
    """
    Returns True if the given float represents an integer value.
    Uses a small tolerance to handle floating‑point precision issues.
    """
    epsilon = 1e-12

    # int(value) truncates toward zero; compare with tolerance.
    truncated = int(value)

    # If the absolute difference is extremely small, treat it as an integer.
    return abs(value - truncated) < epsilon


def print_check(value: float) -> None:
    """
    Prints a descriptive message indicating whether the value is integer-like.
    """
    print(f"Checking value: {value}")

    if is_integer(value):
        print("Result: The value contains an integer.\n")
    else:
        print("Result: The value contains a floating‑point number.\n")


def main():
    """
    Entry point demonstrating several example values.
    """

    # Example input values (Python floats behave like doubles)
    a = 42.0                   # integer-like
    b = 42.00000000001        # floating-point due to tiny fraction
    c = 89.0000000000001      # integer-like
    d = -7.0                  # negative integer-like
    e = 3.14                  # floating-point

    # Run checks
    print_check(a)
    print_check(b)
    print_check(c)
    print_check(d)
    print_check(e)


if __name__ == "__main__":
    main()


"""
run:

Checking value: 42.0
Result: The value contains an integer.

Checking value: 42.00000000001
Result: The value contains a floating‑point number.

Checking value: 89.0000000000001
Result: The value contains an integer.

Checking value: -7.0
Result: The value contains an integer.

Checking value: 3.14
Result: The value contains a floating‑point number.

"""

 



answered Sep 10 by avibootz

Related questions

...