在Python中如何舍入到最近的较低浮点值?

在Python中如何舍入到最近的较低浮点值?,python,formatting,precision,Python,Formatting,Precision,我有一个浮动列表,我想将其四舍五入到2个数字;为此,我使用了以下行: item = ['41618.45110', '1.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '41619.001202', '3468.678822'] print ["{0:.2f}".format(round(float(x), 2)) if re.match("^\d+(\.\d+)?$",

我有一个浮动列表,我想将其四舍五入到2个数字;为此,我使用了以下行:

item = ['41618.45110', '1.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '41619.001202', '3468.678822']
print ["{0:.2f}".format(round(float(x), 2)) if re.match("^\d+(\.\d+)?$", x) else x for x in item]
它将所有列表成员四舍五入到最接近的上浮点数,这将导致
3468.678822
四舍五入到
3468.68
,但我想将它们四舍五入到最接近的下浮点数,因此
3468.678822
应该四舍五入到
3468.67
0有一个例外
;我希望等于
0
的数字保持
0

我尝试在没有
round
甚至
float
函数的情况下使用上述命令,结果是一样的。我还尝试:

[x[:x.index('.')] if re.match("^\d+(\.\d+)?$", x) else x for x in item]

这给了我
未找到子字符串的错误。

您可以使用强制转换来执行此操作:

a = '3468.678822'

def round_2(n):
    return ((int)(n*100)/100)

print(round_2(float(a)))

>>> 3468.67 

我刚刚为这种精确取整做了几个函数。添加了一些关于它如何工作的文档,以防您对它们如何工作感到好奇

import math

def precCeil(num, place = 0):
    """
    Rounds a number up to a given place.

    num - number to round up
    place - place to round up to (see notes)
    """

    # example: 5.146, place is 1

    # move the decimal point to the right or left, depending on
    # the sign of the place
    num = num * math.pow(10, place) # 51.46

    # round it up normally
    num = math.ceil(num) #52

    # put the decimal place back where it was
    num = num * math.pow(10, -place) #5.2

    # return the result rounded, to avoid a weird glitch where
    # a bunch of trailing numbers are added to the result (see notes). 
    return round(num, place) 

""" 
Notes:
Here is how the places work:
0 - ones place
positive ints - to the right of the decimal point
negative ints - to the left of the ones place

This function works perfectly fine on Python 3.4 and 2.7, last I checked.

If you want a version of this that rounds down, just replace the calls 
to math.ceil with calls to math.floor.

Now, the glitch with the trailing numbers. Just have flexCeil return 
num instead of round(num, place). Then test it with flexCeil(12345.12345, 2). 
You get 12345.130000000001.

Interestingly enough, this glitch doesnt happen when you change the
function to round down, instead.
"""