Mona Jalal
Mona Jalal

Reputation: 38165

rounding 1 to have two floating digits

'''
Your task is to write a function which returns the sum of following series upto nth term(parameter).

Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...
'''

Kind of non-trivial but I tried to use round(1,2) to show 1.00 but it shows 1.0, what can I use to show 1.00 in Python?

def series_sum(n):
    # Happy Coding ^_^
    sum = 0
    for i in range(n):
        sum += 1/(1+(3*i))
    return round(sum, 2)

This is a return value for a coding challenge in codewars not a print. so it is supposed to be return and you just write the method.

Upvotes: 0

Views: 5909

Answers (2)

Konstantin Moiseenko
Konstantin Moiseenko

Reputation: 444

Use format function:

return format(sum, '.2f')

Upvotes: 1

UltraInstinct
UltraInstinct

Reputation: 44444

For numerical calculation, the digits after the decimals should not matter. I believe you want a string representation with 2 decimal places.

In Python 2.x, you'd do:

>>> "%.2f"%1.0
'1.00'

In Python3.x, you'd do:

>>> "{:.2f}".format(1.0)
'1.00'

Upvotes: 2

Related Questions