将Python Decimal对象格式化为指定的精度

时间:2013-02-25 20:54:25

标签: python python-2.7 python-3.x decimal

我花了无数个小时研究,阅读,测试,并最终对Python的Decimal对象缺乏最基本的概念感到困惑和沮丧:将Decimal的输出格式化为字符串。

假设我们有一些字符串或Decimal对象具有以下值:

   0.0008
  11.1111
 222.2222
3333.3333
1234.5678

目标是简单地将Decimal的精度设置为小数点后第二位。例如,11.1111格式为11.111234.5678格式为1234.57

我设想的代码类似于以下内容:

import decimal
decimals = [
  decimal.Decimal('0.0008'),
  decimal.Decimal('11.1111'),
  decimal.Decimal('222.2222'),
  decimal.Decimal('3333.3333'),
  decimal.Decimal('1234.5678'),
]
for dec in decimals:
  print dec.as_string(precision=2, rounding=ROUND_HALF_UP)

结果输出为:

0.00
11.11
222.22
3333.33
1234.57

显然我们不能使用Decimal的上下文的精度,因为这会考虑TOTAL位数,而不仅仅是小数精度。

我也不想将Decimal转换为float来输出它的值。 Decimal背后的原因是为了避免在浮点数上存储和运行计算。

还有哪些其他解决方案?我知道堆栈溢出还有许多其他类似的问题,但我找不到解决我所询问的基本问题。

非常感谢!

2 个答案:

答案 0 :(得分:25)

只需使用string formattingformat() function

即可
>>> for dec in decimals:
...    print format(dec, '7.2f')
... 
   0.00
  11.11
 222.22
3333.33
1234.57

decimal.Decimal支持与浮点数相同的format specifications,因此您可以根据需要使用指数,固定点,常规,数字或百分比格式。

这是格式化小数的官方和pythonic方法; Decimal类实现了.__format__()方法来有效地处理这种格式化。

答案 1 :(得分:2)

def d(_in, decimal_places = 3):
    ''' Convert number to Decimal and do rounding, for doing calculations
        Examples:
          46.18271  to   46.183   rounded up
          46.18749  to   46.187   rounded down
          117.34999999999999 to 117.350
         _rescale is a private function, bad practice yet works for now.
    '''
    return Decimal(_in)._rescale(-decimal_places, 'ROUND_HALF_EVEN')

编辑:同样,_rescale()不是由我们常规的Biped使用,它在Python 2.7中有效,在3.4中不可用。