Sachin S
Sachin S

Reputation: 396

Python print issue

I am using below code (simplified for this question):

t1=['1.99','2','133.37']
t2=['4.98','5','11116.98']
t3=list(zip(t1,t2))
t4=[]
for num1,num2 in t3:
  t4.append(float(num1)+float(num2))
print('The sum is='+ ":".join(map(str,t4)))
# output is -> The sum is=6.970000000000001:7.0:11250.35

But I want the output to be as below:

The sum is=6.970000:7.000000:11250.350000
# i.e. six digits ONLY after decimal point

How do I do that?

Upvotes: 1

Views: 116

Answers (4)

Zangetsu
Zangetsu

Reputation: 2015

formatting can be done with %.6f for up to 6 decimal places

t1=['1.99','2','133.37']
t2=['4.98','5','11116.98']
t3=list(zip(t1,t2))
t4=[]
print('The sum is='+ ":"),
for num1,num2 in t3:
    each_sum = float(num1)+float(num2)
    print(":%.6f"%each_sum),

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304117

print('The sum is={:.6f}:{:.6f}:{:.6f}'.format(*t4))

Upvotes: 1

AMADANON Inc.
AMADANON Inc.

Reputation: 5919

t4.append("%.6f" % (float(num1)+float(num2)))

"%.6f" % anumber means convert anumber to a floating point number, then format with 6 digits after the .

Upvotes: 0

icktoofay
icktoofay

Reputation: 128993

Use format:

>>> format(5.2, '.6f')
'5.200000'

The .6 means “to six decimal places” and the f means a floating point number.

To put this into your existing code, use a lambda as the argument to map rather than str:

print('The sum is=' + ":".join(map(lambda n: format(n, '.6f'), t4)))

You could also replace your map call with a generator expression:

print('The sum is=' + ":".join(format(n, '.6f') for n in t4))

Upvotes: 2

Related Questions