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?
12 Réponses
+ 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.
+ 2
if you really wanna take only whole numbers before the dot.:
print(int("45.6".split(".")[0]))
+ 1
Yes, but "56.6" is a string.
55.6 is a float.
try: print(int(55.6))
+ 1
Slick haha alright, just had this doubt, thanks!
+ 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
+ 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
+ 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)
+ 1
DHANANJAY PATEL Younes Damouna thanks got it
0
Slick but if I try print(float('45'))
it gets printed as 45.0
Why doesn't the same happen with int( )?
0
✩✮★✮✩ oh thanks didn't know that
0
Shadoff oh it works, great!
But can you explain what happens in your line of code, like why do we use [0]?
0
Shadoff that's awesome, thanks!