code_junkie

Significant figures in the decimal module

Nov 11th, 2011
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. from decimal import Decimal
  2. >>> Decimal('1.0') + Decimal('2.0')
  3. Decimal("3.0")
  4.  
  5. >>> Decimal('1.00') / Decimal('3.00')
  6. Decimal("0.3333333333333333333333333333")
  7.  
  8. decimal.getcontext().prec=2
  9.  
  10. decimal.getcontext().prec=2
  11.  
  12. >>> "%8.2e"% ( 1.0/3.0 )
  13. '3.33e-01'
  14.  
  15. def lround(x,leadingDigits=0):
  16. """Return x either as 'print' would show it (the default)
  17. or rounded to the specified digit as counted from the leftmost
  18. non-zero digit of the number, e.g. lround(0.00326,2) --> 0.0033
  19. """
  20. assert leadingDigits>=0
  21. if leadingDigits==0:
  22. return float(str(x)) #just give it back like 'print' would give it
  23. return float('%.*e' % (int(leadingDigits),x)) #give it back as rounded by the %e format
  24.  
  25. >>> lround(1./3.,2),str(lround(1./3.,2)),str(lround(1./3.,4))
  26. (0.33000000000000002, '0.33', '0.3333')
Add Comment
Please, Sign In to add comment