I was trying to replicate Python's internal round() function. The program asks for a number, converts it into a float (catches the value error if present) and gets the absolute value of the float (to handle negative numbers).
def rounder():
number = input("Give me a number to round off!: \n")
#Makes sure you enter a valid number
try:
floater = float(number)
absol = abs(floater)
except ValueError:
print("Please enter a valid number.\n")
starter()
if absol < 10 and absol > 0: #Works for both 0.6 and 1.6 | Because 0.6 is too small for 1 and will return the rounding while 1.6 % == 0.6 also
rounding = absol % 1
if rounding >= 0.5: #If more than 0.5
absol += 1 #Increment It
temp =(int(absol)) #Convert back to integer
if floater < 0: #Negative check
print(-temp)
else:
print(temp)
elif rounding < 0.5:
temp = (int(absol))
if floater < 0: #Negative check
print(-temp)
else:
print(temp)
elif absol < 100 and absol > 10: #use %10
rounding = absol % 10
rounding2 = rounding % 1
if rounding2 >= 0.5: #If more than 0.5
absol += 1 #Increment It
temp = (int(absol)) #Convert back to integer
if floater < 0: #Negative check
print(-temp)
else:
print(temp)
elif rounding2 < 0.5:
temp = (int(absol))
if floater < 0: #Negative check
print(-temp)
else:
print(temp)
rounder()
def starter():
print("Compatible from 0.1 - 9999.9")
rounder()
starter()
It keeps on going like that until if absol < 10000 and absol > 1000
. Also the number of modulo operations (%) it goes through increases.
The ranges are hard-coded so it can only handle numbers from 1 - 10 000. I could manually increase the limitation if I wanted but I would have to keep doing that until infinity.
Does anyone have any idea on how to get beyond this limitation?
Can my code be refined? Is there a more efficient way of doing this?
Keep all answers beginner-friendly.