Reputation: 189
```python
import decimal
x=[]
#functions etc. x is changed
#now returns is a list full of integers
print(sum(x)/len(x))
#This happens to give 0.6999
print(decimal.Decimal(sum(x)/len(x))
# This happens to give 0.6998999999996034 blah blah blah
```
The decimal module gives too many decimal places and round(decimal.Decimal(x),5) gives 0.69990
I would like it to output 0.69999(5 d.p.) but it outputs 0.6999 or 0.69990
Upvotes: 0
Views: 686
Reputation: 106
you already have the right answer: round(decimal.Decimal(x),5)
which gives 0.69990
. In your case, you should not expect 0.69999
, it is not even close to 0.699899999999
.
The python built-in function round
is good to use, but sometimes it can be surprising, see more details here
To summary:
import decimal
x=0.699899999
print("x =", x)
g = round(decimal.Decimal(x),5)
print("rounded:", g)
output:
x = 0.699899999
rounded: 0.69990
Upvotes: 1
Reputation: 104752
The number 0.699899999999...
is mathematically equivalent to 0.6999000...
, assuming the 9
s repeat farther than we want to go before we round things off.
This is the same as the question of why 0.9999...
is equal to 1
(for which you can find many explanations online, I'm fond of this one myself), just shifted several decimal places to the right. All the 9
s at the end turn into a 1
. That one gets added to the last 8
and turn it into a 9
. That's all followed by infinite zeros, which Python omits by default.
Upvotes: 0
Reputation: 206
You can try something like this
x=0.6999932
g = float("{0:.5f}".format(x))
print(g)
#output be like
0.69999
Upvotes: 1