How to round each item in a list of floats to 2 decimal places?

前端 未结 6 1979
有刺的猬
有刺的猬 2021-01-31 07:20

I have a list which consists of float values but they\'re too detailed to proceed. I know we can shorten them by using the (\"%.f\" % variable) operator, like:

6条回答
  •  深忆病人
    2021-01-31 07:41

    You might want to look at Python's decimal module, which can make using floating point numbers and doing arithmetic with them a lot more intuitive. Here's a trivial example of one way of using it to "clean up" your list values:

    >>> from decimal import *
    >>> mylist = [0.30000000000000004, 0.5, 0.20000000000000001]
    >>> getcontext().prec = 2
    >>> ["%.2f" % e for e in mylist]
    ['0.30', '0.50', '0.20']
    >>> [Decimal("%.2f" % e) for e in mylist]
    [Decimal('0.30'), Decimal('0.50'), Decimal('0.20')]
    >>> data = [float(Decimal("%.2f" % e)) for e in mylist]
    >>> data
    [0.3, 0.5, 0.2]
    

提交回复
热议问题