python中保留两位小数

时间:2023-09-26 19:54:14

今天写程序的时候碰到了一个问题关于如何控制浮点数只显示小数点后两位,正常的想法是用round函数,例如 round(a, 2),但是在面对下面的问题时候round就不太好用了

>>> a=13.949999999999999

>>> round(a, 2)

13.949999999999999

上网查了资料,有网友提供了一种方法

print('%.2f'%a)

>>>13.95

另外还可以用 trunc(a,2)截取函数

>>>13.94

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

定义Decimal数据类型:

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

2 定义方式如下:

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

如果需要从浮点数据转换为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)

fromimport,Decimal>>>().=6>>>Decimal'50.567898491579878'  1Decimal'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)

fromimport,Decimal>>>().=6>>>Decimal'50.567898491579878'
Decimal'50.567898491579878'
# Shouldn't that have been rounded to 6 digits on instantiation?>>>Decimal'50.567898491579878'  1Decimal'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.>>>fromimportDecimal>>># Is the following the correct way to get the value into 2 decimal places,>>># or is there a "better" way?>>>=Decimal'50.5679'quantizeDecimal'0.00'
# Just wanted to see what the value wasDecimal'50.57'
()>>>本机测试用例:
  1. >>> import decimal
  2. >>> x = decimal.Decimal(87345)
  3. >>> x
  4. Decimal('87345')
  5. >>> print x
  6. 87345
  7. >>> from decimal import getcontext, Decimal
  8. >>> x = Decimal('0.998531571219').quantize(Decimal('0.00'))
  9. >>> x
  10. Decimal('1.00')
  11. >>> print x
  12. 1.00
  13. >>> x = Decimal('0.998531571219').quantize(Decimal('0.0000'))
  14. >>> x
  15. Decimal('0.9985')
  16. >>> print x
  17. 0.9985
  18. >>> y = Decimal.from_float(0.998531571219)
  19. >>> y
  20. Decimal('0.99853157121900004700165709436987526714801788330078125')
  21. >>> y = Decimal.from_float(0.998531571219).quantize(Decimal('0.0000'))
  22. >>> y
  23. Decimal('0.9985')
  24. >>> print y
  25. 0.9985
  26. >>> f1 = 0.998531571219
  27. >>> f1
  28. 0.998531571219
  29. >>> type(f1)
  30. <type 'float'>
  31. >>> f2 = str(f1)
  32. >>> f2
  33. '0.998531571219'
  34. >>> type(f2)
  35. <type 'str'>
  36. >>>