Tuesday, August 9, 2022

[FIXED] How do I get decimals values without rounding them off

Issue

How do I add two numbers and retain their decimal places in the final answer? Below is the code to do this but it does not work.

import re
cnt=0
s=0
l1= []
with open('C://Users/S/Documents/ok5.txt') as f:
    for i in f:
        if i.startswith('X-DSPAM-Confidence:'):
            x = re.findall('\d*?\.\d+',i)
            l1.append(x)
            cnt+=1

for i in range(0,len(l1)):
    j = float(i)
    s += j

print(l1)    
print(s)

The output I get is:

[['0.5454'], ['0.5677']]
1.0

But, when I try the simple code below it gives the right answer:

a = 0.5454
b = 0.5677
c = float(a+b)
print(c)

The output for this is:

1.1131

Solution

I think you want to do this instead:

import re
cnt=0
s=0
l1= []
with open('C://Users/S/Documents/ok5.txt') as f:
    for i in f:
        if i.startswith('X-DSPAM-Confidence:'):
            x = re.findall('\d*?\.\d+',i)
            l1.append(x)
            s += float(x[0]) # You could just add it here, which improves time complexity
            cnt+=1
print(l1)    
print(s)


Answered By - jbflow
Answer Checked By - Mary Flores (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.