Open In App

Python | Convert tuple to float value

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with tuple, we can have a problem in which, we need to convert a tuple to floating-point number in which first element represents integer part and next element represents a decimal part. Let’s discuss certain way in which this can be achieved. 
Method : Using join() + float() + str() + generator expression The combination of above functionalities can solve this problem. In this, we 1st convert the tuple elements into a string, then join them and convert them to desired integer. 

Python3




# Python3 code to demonstrate working of
# Convert tuple to float
# using join() + float() + str() + generator expression
 
# initialize tuple
test_tup = (4, 56)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# Convert tuple to float
# using join() + float() + str() + generator expression
res = float('.'.join(str(ele) for ele in test_tup))
 
# printing result
print("The float after conversion from tuple is : " + str(res))


Output

The original tuple : (4, 56)
The float after conversion from tuple is : 4.56

Method #2 : Using format() + join()
This method is similar to the above method but instead of using generator expression, we use the join() function with format() method to convert the tuple elements into a string.

Python3




# Python3 code to demonstrate working of
# Convert tuple to float
# using format() + join()
 
# initialize tuple
test_tup = (4, 56)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# Convert tuple to float
# using format() + join()
res = float("{}.{}".format(*test_tup))
 
# printing result
print("The float after conversion from tuple is : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original tuple : (4, 56)
The float after conversion from tuple is : 4.56

Time complexity : O(1)
Auxiliary Space : O(1)

Method #3: Using math and tuple unpacking

  1. Import the math module
  2. Unpack the tuple into separate variables using tuple unpacking
  3. Divide the first element by 10^d, where d is the number of digits in the second element
  4. Add the quotient from step 3 to the second element, to get a float

Python3




import math
 
# initialize tuple
test_tup = (4, 56)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# Convert tuple to float using math and tuple unpacking
a, b = test_tup
res = a + (b / math.pow(10, len(str(b))))
 
# round the result to 2 decimal places
res = round(res, 2)
 
# printing result
print("The float after conversion from tuple is : " + str(res))


Output

The original tuple : (4, 56)
The float after conversion from tuple is : 4.56

Time complexity: O(1)
Auxiliary space: O(1)



Last Updated : 23 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads