1

I have written the following code:

typConvInt = int('3.3')
print(typConvInt)

But compiler is throwing an error.

ErrorMessage:

Traceback (most recent call last):
  File "E:\Trainings\Python_Training\HelloWorld.py", line 285, in <module>
    intconv3 = int('3.3')
               ^^^^^^^^^^
ValueError: invalid literal for int() with base 10: '3.3'

Version: Python 2.7.7

I tried to change the float to integer value it worked but it still failing with the float string to integer conversion

conv1 = int('3')
print(conv1) 
# this is passed

conv2 = int('3.0')
print(conv2)
# this code is still failing but the tutorial says this will work and return as 3

Documentation: https://docs.python.org/3/library/stdtypes.html

2
  • Unless you have a good reason (supporting legacy code, for example), you should be using Python 3, not Python 2.7.
    – chepner
    Commented Jul 8 at 12:16
  • You cannot use string if you convert to int. Should be typConvInt = int(3.3) <== remove string. If you want print 3.3 then float(3.3) will do. Commented Jul 8 at 12:23

2 Answers 2

1

int() can convert strings containing integer literals into int.

It can also handle floating-point number, but it cannot (directly) convert string that contain floating-point number, into int.

You can convert a string to a float and then float to int like this:

print(int(float("3.14")) # prints 3
0

The error occurred because you are trying to convert a string representing a float ('3.3' or '3.0') directly to an int, which is not allowed in Python. The int() function expects a string that represents an integer.

To convert a float string to an integer, you need first to convert the string to a float and then convert the float to an integer.

# First convert the string to a float
 fVal= float('3.3')

 # Then convert the float to an integer
 intVal= int(fVal)

 print(intVal)

Hope this will help

Not the answer you're looking for? Browse other questions tagged or ask your own question.