开发者

How can I write a function in Python that rounds a number?

开发者 https://www.devze.com 2023-02-07 09:18 出处:网络
How can I write a function in Python that rounds a number, in the usua开发者_开发知识库l fashion.

How can I write a function in Python that rounds a number, in the usua开发者_开发知识库l fashion. Numbers less than .5 round down, and .5 and above rounds up.

3.4 -> 3

11.9 -> 12

5.5 -> 6


Use the Python function round(). If you want to do it yourself, add 0.5 and then truncate.


def roundNumberAccordingly(number):
    digits = str(number)

    integer = 0
    remainder = 0
    seen_decimal = False
    for i in range(len(digits)):
        if digits[i] == '.':
            seen_decimal = True
            continue
        elif not seen_decimal:
            delta = int(digits[i]) * 10 ** (len(digits) - i - 1)
            integer += delta
        else:
            delta = int(digits[i]) * 10 ** (len(digits) - i - 1)
            remainder += delta
    integer /= 10 ** (len(str(remainder)) + 1)
    print integer
    print remainder

    first = str(remainder)[0]
    if first in ('0', '1', '2', '3', '4'):
        return integer
    else:
        return integer + 1

Just kidding ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消