I'm stuck on a beginner level coding problem. Goal is to round a float number and output an integer. So x = 3.14159
, output 3
(not 3.0
). We're supposed to be able to do this using only what we've learned, and what we've learned is only 3 functions: .find
, <string>[:]
, and converting the given x = float num
into a string, via str()
.
How should I be thinking about this? When I write out what logically needs to happen, I always find myself needing if()
.
I ended up getting partial credit with the following code:
given: x = 3.14159
x = int(round(x))
print x
But I would like to solve it without int()
or round()
, or if()
. My first thought was to use x[2:3]
and x[3:4]
to check the tenths and hundredths place values, but to proceed I still run into the if()
wall.
This is a poorly constructed string manipulation problem because you'd never actually go about solving this problem this way. But using only what you've been taught, you can accomplish the task:
x = 3.14159
# 0.5 (optional?) add 0.5 to x so that it will be properly rounded
# when removing the digits after the decimal
x += 0.5
# 1. convert the int to a string
x_str = str(x)
# 2. find the index of the decimal point in the string
decimal_idx = x_str.find('.')
# 3. slice the string from the beginning to the decimal
x_int_str = x_str[:decimal_idx]
# 4. do something with the value
print(x_int_str)