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 ;)
精彩评论