设为首页 收藏本站
查看: 860|回复: 0

[经验分享] python Decimal 使用

[复制链接]

尚未签到

发表于 2017-4-24 12:16:39 | 显示全部楼层 |阅读模式
  地址:http://docs.python.org/library/decimal.html
  Decimal支持大多数的数学操作。使用decimal的时候是在一个context背景下工作的。可以使用getcontext来获得当前背景:
  from decimal import *
  c = getcontext()
  print c
  结果:
  Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, capitals=1, flags=[], traps=[Overflow, InvalidOperation, DivisionByZero])
  使用Decimal,int类型可以直接用来构造Decimal,但是float类型的变量要先转换为字符串。在进行运算之后结果会使用getcontext().prec来确定精度,例如prec为5的时候,100.1234567890+0会等于100.12:
  # -*- coding: cp936 -*-
  from decimal import *
  con = getcontext()
  print '-----------------------context------------------------'
  print con
  a = Decimal(100)
  print a
  b = Decimal('100.001')
  print b
  print '--------------------------prec------------------------------'
  c = Decimal('100.1234567890')
  print c
  con.prec = 5
  print con
  d = Decimal('100.1234567890')
  print 'd:',d
  print 'd+0:',d+0
  结果:
  >>>
  -----------------------context------------------------
  Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, capitals=1, flags=[], traps=[DivisionByZero, InvalidOperation, Overflow])
  100
  100.001
  --------------------------prec------------------------------
  100.1234567890
  Context(prec=5, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, capitals=1, flags=[], traps=[DivisionByZero, InvalidOperation, Overflow])
  d: 100.1234567890
  d+0: 100.12
  可以修改Context来改变Decimal运算的行为,例如精度、如何舍弃位数等等。例如下面的程序测试各种rounding设置对结果的影响:
  # -*- coding: cp936 -*-
  from decimal import *
  con = getcontext()
  con.prec = 5
  print '-----------------------context------------------------'
  print con
  s = '100.005'
  strs = [
  '100.005',
  '100.004',
  '-100.005',
  '-100.004',
  ]
  round_methods = [
  ROUND_CEILING,
  ROUND_DOWN,
  ROUND_FLOOR,
  ROUND_HALF_DOWN,
  ROUND_HALF_EVEN,
  ROUND_HALF_UP,
  ROUND_UP,
  ROUND_05UP,
  ]
  for method in round_methods:
  con.rounding = method
  print '----------------------------', con.rounding, '----------------------------'
  for s in strs:
  print ' %s+0:' % s, Decimal(s)+0
  结果:
  >>>
  -----------------------context------------------------
  Context(prec=5, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, capitals=1, flags=[], traps=[DivisionByZero, Overflow, InvalidOperation])
  ---------------------------- ROUND_CEILING ----------------------------
  100.005+0: 100.01
  100.004+0: 100.01
  -100.005+0: -100.00
  -100.004+0: -100.00
  ---------------------------- ROUND_DOWN ----------------------------
  100.005+0: 100.00
  100.004+0: 100.00
  -100.005+0: -100.00
  -100.004+0: -100.00
  ---------------------------- ROUND_FLOOR ----------------------------
  100.005+0: 100.00
  100.004+0: 100.00
  -100.005+0: -100.01
  -100.004+0: -100.01
  ---------------------------- ROUND_HALF_DOWN ----------------------------
  100.005+0: 100.00
  100.004+0: 100.00
  -100.005+0: -100.00
  -100.004+0: -100.00
  ---------------------------- ROUND_HALF_EVEN ----------------------------
  100.005+0: 100.00
  100.004+0: 100.00
  -100.005+0: -100.00
  -100.004+0: -100.00
  ---------------------------- ROUND_HALF_UP ----------------------------
  100.005+0: 100.01
  100.004+0: 100.00
  -100.005+0: -100.01
  -100.004+0: -100.00
  ---------------------------- ROUND_UP ----------------------------
  100.005+0: 100.01
  100.004+0: 100.01
  -100.005+0: -100.01
  -100.004+0: -100.01
  ---------------------------- ROUND_05UP ----------------------------
  100.005+0: 100.01
  100.004+0: 100.01
  -100.005+0: -100.01
  -100.004+0: -100.01
  >>>
  文档里有一个将Decimal转换为现金格式的函数:
  def moneyfmt(value, places=2, curr='', sep=',', dp='.',
  pos='', neg='-', trailneg=''):
  """Convert Decimal to a money formatted string.
  places:  required number of places after the decimal point
  curr:    optional currency symbol before the sign (may be blank)
  sep:     optional grouping separator (comma, period, space, or blank)
  dp:      decimal point indicator (comma or period)
  only specify as blank when places is zero
  pos:     optional sign for positive numbers: '+', space or blank
  neg:     optional sign for negative numbers: '-', '(', space or blank
  trailneg:optional trailing minus indicator:  '-', ')', space or blank
  >>> d = Decimal('-1234567.8901')
  >>> moneyfmt(d, curr='$')
  '-$1,234,567.89'
  >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
  '1.234.568-'
  >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
  '($1,234,567.89)'
  >>> moneyfmt(Decimal(123456789), sep=' ')
  '123 456 789.00'
  >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
  '<0.02>'
  """
  q = Decimal(10) ** -places      # 2 places --> '0.01'
  sign, digits, exp = value.quantize(q).as_tuple()
  result = []
  digits = map(str, digits)
  build, next = result.append, digits.pop
  if sign:
  build(trailneg)
  for i in range(places):
  build(next() if digits else '0')
  build(dp)
  if not digits:
  build('0')
  i = 0
  while digits:
  build(next())
  i += 1
  if i == 3 and digits:
  i = 0
  build(sep)
  build(curr)
  build(neg if sign else pos)
  return ''.join(reversed(result))
  本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/runningtortoise/archive/2009/07/19/4361494.aspx

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-368653-1-1.html 上篇帖子: python is obvious ! 下篇帖子: python challenge 9
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表