PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 9, 2022

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

 August 09, 2022     decimal, file, floating-point, python, python-3.x     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing