관리 메뉴

Jun Hyuk Kim's Blog

[Python] About round function in python 본문

Coding Problems

[Python] About round function in python

junhyuk1229 2023. 9. 22. 13:50

So this happened when I tried to solve a programming problem using python's round function.

Some errors from test cases were found and I was trying to find out why those errors were happening.

round(0.5) = 0 ???
round(1.5) = 2
round(2.5) = 2 ???

The rounding that we learn usually is where the number is rounded up if the number after the decimal is 5 or larger. So why are the results above happening?

The python function round uses the 'to nearest, ties to even' as the standard to round the number hence the results being only even. The standard we are used to is the 'toward +inf' way, so how can we use the original formula without using the round function? My solution was to make a function to get the results.

def round_digit(x):
	# Get float after period
	temp_float = x - math.floor(x)

	# If float is less than 0.5
	if temp_float < 0.5:
		return math.floor(x)

	# Else
	return math.ceil(x)