python中保留两位小数

>>> a=13.949999999999999
>>> round(a, 2)
13.949999999999999

>>> print "%.2f" % a
13.95


还可以使用decimal

decimal.Decimal类型是Python中满足高精度计算的一种数据类型，使用进需要导入decimal包

1 无法使用赋字面值的方式定义

2 定义方式如下：

>>> import decimal >>> x = decimal.Decimal(87345) >>> x Decimal('87345') >>> x = decimal.Decimal('123.3344332566334') >>> x Decimal('123.3344332566334') 可以传递给Decimal整型或者字符串参数，但不能是浮点数据，因为浮点数据本身就不准确

>>> x = decimal.Decimal.from_float(127.3323)
>>> x
Decimal('127.332300000000003592504072003066539764404296875')

I have 3 questions pertaining to decimal arithmetic in Python, all 3 of which are best asked inline:

1)

>>> from decimal import getcontext, Decimal
>>> getcontext().prec = 6
>>> Decimal('50.567898491579878') * 1
Decimal('50.5679')
>>> # How is this a precision of 6? If the decimal counts whole numbers as
>>> # part of the precision, is that actually still precision?
>>> 

and

2)

>>> from decimal import getcontext, Decimal
>>> getcontext().prec = 6
>>> Decimal('50.567898491579878')
Decimal('50.567898491579878')
>>> # Shouldn't that have been rounded to 6 digits on instantiation?
>>> Decimal('50.567898491579878') * 1
Decimal('50.5679')
>>> # Instead, it only follows my precision setting set when operated on.
>>> 

3)

>>> # Now I want to save the value to my database as a "total" with 2 places.
>>> from decimal import Decimal
>>> # Is the following the correct way to get the value into 2 decimal places,
>>> # or is there a "better" way?
>>> x = Decimal('50.5679').quantize(Decimal('0.00'))
>>> x  # Just wanted to see what the value was
Decimal('50.57')
>>> foo_save_value_to_db(x)
>>> 

本机测试用例：
>>> import decimal
>>> x = decimal.Decimal(87345)
>>> x
Decimal('87345')
>>> print x
87345
>>> from decimal import getcontext, Decimal
>>> x = Decimal('0.998531571219').quantize(Decimal('0.00'))
>>> x
Decimal('1.00')
>>> print x
1.00
>>> x = Decimal('0.998531571219').quantize(Decimal('0.0000'))
>>> x
Decimal('0.9985')
>>> print x
0.9985
>>> y = Decimal.from_float(0.998531571219)
>>> y
Decimal('0.99853157121900004700165709436987526714801788330078125')
>>> y = Decimal.from_float(0.998531571219).quantize(Decimal('0.0000'))
>>> y
Decimal('0.9985')
>>> print y
0.9985
>>> f1 = 0.998531571219
>>> f1
0.998531571219
>>> type(f1)
<type 'float'>
>>> f2 = str(f1)
>>> f2
'0.998531571219'
>>> type(f2)
<type 'str'>
>>>