Advertisement
rfmonk

decimal_rounding.py

Jan 22nd, 2014
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3.  
  4. import decimal
  5.  
  6. context = decimal.getcontext()
  7.  
  8. ROUNDING_MODES = [
  9.     'ROUND_CEILING',
  10.     'ROUND_DOWN',
  11.     'ROUND_FLOOR',
  12.     'ROUND_HALF_DOWN',
  13.     'ROUND_HALF_EVEN',
  14.     'ROUND_HALF_UP',
  15.     'ROUND_UP',
  16.     'ROUND_05UP',
  17. ]
  18. header_fmt = '{:10} ' + ' '.join(['{:^8}'] * 6)
  19.  
  20. print header_fmt.format(' ',
  21.                         '1/8 (1)', '-1/8 (1)',
  22.                         '1/8 (2)', '-1/8 (2)',
  23.                         '1/8 (3)', '-1/8 (3)',
  24.                         )
  25.  
  26. for rounding_mode in ROUNDING_MODES:
  27.     print '{0:10}'.format(rounding_mode.partition('_')[-1]),
  28.     for precision in [1, 2, 3]:
  29.         context.prec = precision
  30.         context.rounding = getattr(decimal, rounding_mode)
  31.         value = decimal.Decimal(1) / decimal.Decimal(8)
  32.         print '{0:^8}'.format(value),
  33.         value = decimal.Decimal(-1) / decimal.Decimal(8)
  34.         print '{0:^8}'.format(value),
  35.     print
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement