2016-10-16 4 views
1

У меня есть список поплавков, которые я хочу округлить до двух чисел; Я использовал ниже линии для этой цели:Как округлить до ближайшего нижнего плавания в Python?

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] 

Который дал мне Substring not found ошибку.

ответ

1

Вы можете использовать бросок, чтобы сделать это:

a = '3468.678822' 

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

print(round_2(float(a))) 

>>> 3468.67 
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. 
""" 
Смежные вопросы