Check whether given floating point number is even or odd in Python

Determining whether a floating-point number is even or odd requires a different approach than integers. We cannot simply check the last digit by dividing by 2, since floating-point numbers have decimal parts that need special handling.

The key insight is to find the first significant digit from right to left (ignoring trailing zeros after the decimal point) and check if that digit is even or odd.

Example

For the number 200.290, we ignore the trailing zero and check the digit 9, which makes the number odd.

Algorithm

The approach involves these steps ?

  • Convert the number to a string
  • Traverse from right to left
  • Skip trailing zeros after the decimal point
  • Return the parity of the first significant digit encountered

Implementation

def check_float_parity(n):
    s = str(n)
    
    flag = False
    for i in range(len(s) - 1, -1, -1):
        # Skip trailing zeros after decimal point
        if s[i] == '0' and flag == False:
            continue
        
        # Mark that we've passed the decimal point
        if s[i] == '.':
            flag = True
            continue
        
        # Check if the first significant digit is even
        if int(s[i]) % 2 == 0:
            return "Even"
        else:
            return "Odd"

# Test with different examples
numbers = [200.290, 123.450, 567.000, 24.68]

for num in numbers:
    result = check_float_parity(num)
    print(f"{num} is {result}")
200.290 is Odd
123.45 is Odd
567.0 is Odd
24.68 is Even

How It Works

The algorithm processes the string representation from right to left ?

  1. Skip trailing zeros: 200.290 → ignore the trailing 0
  2. Find first significant digit: The digit 9 is encountered first
  3. Check parity: Since 9 % 2 != 0, the number is odd

Alternative Approach

A simpler method using string manipulation ?

def check_parity_simple(n):
    # Remove trailing zeros and decimal point
    s = str(n).rstrip('0').rstrip('.')
    
    # Get the last remaining digit
    last_digit = int(s[-1])
    
    return "Even" if last_digit % 2 == 0 else "Odd"

# Test the alternative approach
test_numbers = [200.290, 123.450, 24.68, 100.00]

for num in test_numbers:
    result = check_parity_simple(num)
    print(f"{num} is {result}")
200.290 is Odd
123.45 is Odd
24.68 is Even
100.0 is Even

Conclusion

To check if a floating-point number is even or odd, find the rightmost significant digit (ignoring trailing zeros) and test its parity. The string manipulation approach provides an elegant solution to handle the decimal point complexities.

Updated on: 2026-03-25T14:35:19+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements