0

Why do I get error here?

https://code.sololearn.com/cpYYni9RpGZn/?ref=app Why do I get error when I try to convert a string which has a float value into an actual integer? Doesn't the int( ) take care of the conversion of float to int?

24th Jul 2021, 3:15 PM
Srinath
12 Respostas
+ 3
Don't know exactly. Has something to do with how python handles floats. It's the whole: "a square is a rectangle, but a rectangle is not a square" thing, but you can look it up yourself if you really wanna know. Either way, print(int(float("56.6"))) would work.
24th Jul 2021, 3:21 PM
Slick
Slick - avatar
+ 2
if you really wanna take only whole numbers before the dot.: print(int("45.6".split(".")[0]))
24th Jul 2021, 3:35 PM
Shadoff
Shadoff - avatar
+ 1
Yes, but "56.6" is a string. 55.6 is a float. try: print(int(55.6))
24th Jul 2021, 3:17 PM
Slick
Slick - avatar
+ 1
Slick haha alright, just had this doubt, thanks!
24th Jul 2021, 3:25 PM
Srinath
+ 1
Verstappen , x = "45.6" #this is string which has dot y = x.split(".") #this will create list separating string into substrings where dot occurred. # y = ["45","6"] z = y[0] #zero indexed item of list y z2 = int(z) # int("45") converts string to integer then we just print it. #And all those in one line
25th Jul 2021, 4:07 AM
Shadoff
Shadoff - avatar
+ 1
Verstappen It is all about parsing string variable to either int or float. when input() reads string from standard input, it needs to be converted to int or float, if string represent float it converts string to float by calling float(input()) to float variable. Likewise int(input()) converts string to int by calling int(input()) to int variable. If float value is converted to int there is a loss of information. As well as when we read input from either standard input, file, or string. If we read float value as int then there will be problem in reading next value from input(). This is why float value should be read as float and int value as int. DHANANJAY PATEL
26th Jul 2021, 2:44 PM
DHANANJAY PATEL
DHANANJAY PATEL - avatar
+ 1
First of all You should convert the string into a float then pass it to the int() function. x="13.5" float_num=float(x) int_num=int(float_num)
26th Jul 2021, 2:49 PM
Younes Damouna
Younes Damouna - avatar
26th Jul 2021, 3:04 PM
Srinath
0
Slick but if I try print(float('45')) it gets printed as 45.0 Why doesn't the same happen with int( )?
24th Jul 2021, 3:18 PM
Srinath
0
âœ©âœźâ˜…âœźâœ© oh thanks didn't know that
24th Jul 2021, 3:26 PM
Srinath
0
Shadoff oh it works, great! But can you explain what happens in your line of code, like why do we use [0]?
24th Jul 2021, 3:40 PM
Srinath
0
Shadoff that's awesome, thanks!
25th Jul 2021, 4:23 AM
Srinath