Problem converting string to decimal number

49 Views Asked by At

Where is the problem with this code?

def my_average(*num):
    s, count = 0, 0
    for nums in num:
        if type(nums) == int:
            s += nums

        elif type(nums) == float:
            s += nums

        elif type(nums) == str:
            for k in nums:
                float_num = float(k)
                s += float_num

        count += 1
    return round(s / count, 2)

test_case = (2, 3, 25, '234.123123', 3, 1, 0)
print(my_average(*test_case))

Actually, I wanted to convert the decimal string into a decimal number and use it in my calculations.

3

There are 3 best solutions below

0
Diego Torres Milano On

To convert the entire tuple to float you can use

map(float, test_case)

which you can sum with

sum(map(float, test_case))

and get the average

sum(map(float, test_case))/len(test_case)
2
TheMaster On

You're looping through each character in the string here: for k in nums:, which causesfloat(k) to try to convert the . character. Remove it

        elif type(nums) == str:
            # for k in nums:
                float_num = float(nums)
                s += float_num
0
SIGHUP On

Just try to convert everything to float:

def my_average(*args):
    if args:
        return sum(map(float, args)) / len(args)

test_case = (2, 3, 25, '234.123123', 3, 1, 0)
print(my_average(*test_case))

Output:

38.30330328571428