Swapping numbers before and after decimal

Observe the comments I put in your code to better understand what is happening:

def float_swap(x): # 2.5
    a = x - int(x) # a = 2.5 - 2 = 0.5
    b = int(x)     # b = 2
    return str(b+a)# str(2 + 0.5)

print(float_swap(2.5))
# 2.5 

The correct way would be

def float_swap(x): # 2.5
    return '.'.join(str(float(x)).split('.')[::-1])

print(float_swap(2.5))
print(float_swap(37))

Output:

5.2
0.37

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top