Reputation: 611
Example to show my usecase:
from __future__ import division
a = 215 / 4
print a # Case 1. Should print 53.75
a = 215 / 3
print a # Case 2. Should print 71.6666666666666714 i.e. decimal to 16 precision.
Possible solutions which don't work:
print str(a) # Case 2 gets printed with only 12 precision (needed 16)
print repr(a) # Case 2 gets printed as 71.66666666666667 (precision 14, needed 16)
print '{0:.16f}'.format(a) # Case 1 gets printed with trailing zeroes
print '{0:.16g}'.format(a) # Decimal precision is 14, needed 16.
What would be the best pythonic solution to this?
Edit: If precision of 16 is a limitation of float
division, what would be the pythonic way to get 8 decimals place precision. Is there a better soln. than '{0:.8f}'.format(a).rstrip('0')
?
Upvotes: 1
Views: 1229
Reputation: 159
I believe getcontext() will be your friend here, in the decimal library.
This allows you to set precision and manipulate significant figure outcomes.
https://docs.python.org/2/library/decimal.html
Upvotes: 1