如何在Python中舍入到最近的下浮点?

时间:2016-10-16 13:34:52

标签: 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+)?$", x) else x for x in item]

它将所有列表成员四舍五入到最近的上浮点,导致3468.678822四舍五入为3468.68,但我想将它们舍入到最近的下浮点数,因此3468.678822应该舍入到3468.670有一个例外;我希望等于0的数字保持0

我尝试使用上面的命令而没有round甚至float函数,结果是一样的。我也尝试过:

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

这给了我Substring not found错误。

2 个答案:

答案 0 :(得分:1)

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

a = '3468.678822'

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

print(round_2(float(a)))

>>> 3468.67 

答案 1 :(得分:0)

我刚刚为这种精确舍入做了几个函数。添加了一些有关其工作原理的文档,以防您对它们的工作方式感到好奇。

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.
"""