Int function and decimal number | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Int function and decimal number

Dear friends, I wonder why the following code when the input is a decimal number will not work. x = int (input ("Enter a number: ")) print(x) when e.g. you put 123.97, it returns an error! I suppose it gives back 123 just as the int(123.97) does when written directly in the IDLE, but it does not. I cannot understand the error. Could any of you kindly help me to find the answer?

7th Apr 2017, 8:34 PM
Mohammad R. Arastoo
Mohammad R. Arastoo - avatar
8 Answers
+ 1
when converting from a string, you need the exact conversion. if the string is "173.99", you would use float(). if the string is "82", you would use int () (or float (), but then you would get 82.0). so since the string has a decimal, you need to use float () first, and then in a second line you can convert it using int ()
7th Apr 2017, 8:46 PM
Edward
+ 1
cause int( ) means you are trying to convert the string to a integer, but if its not an integer (like 123.97 which is a float), it will cause an error.
7th Apr 2017, 8:37 PM
Edward
+ 1
x = float(input ("Enter a number: ")) print(int(x)) try this instead
7th Apr 2017, 8:40 PM
Edward
+ 1
x = float(input ("Enter a number: ")) int(x) print(x) it has to be done in two steps. first the proper string conversion, then you can cut off the decimal my converting the floating point number to an integer. still have doubts?
7th Apr 2017, 8:48 PM
Edward
+ 1
no problem buddy
7th Apr 2017, 8:52 PM
Edward
0
Dear Edward, thank for your reply. But, why it does not give any error when running int(123.97) directly in the IDLE? The error says something about "int base in 10"
7th Apr 2017, 8:40 PM
Mohammad R. Arastoo
Mohammad R. Arastoo - avatar
0
Dear Edward. I know this code. I just wonder why the error should come up? Why float() does not give back the error?
7th Apr 2017, 8:44 PM
Mohammad R. Arastoo
Mohammad R. Arastoo - avatar
0
Thank you for your kind response Edward. :)
7th Apr 2017, 8:48 PM
Mohammad R. Arastoo
Mohammad R. Arastoo - avatar