Datatype conversion

Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!


Once in a while you will want to convert data type of one type to another type. Data type conversion is also known as Type casting.

Converting int to float

To convert int  to float  you need to use float() function.

Converting float to int

To convert float  to int  you need to use int() function.

Converting string to int

You can also use int()  to convert string  to int

Note: If string contains non numeric character then int()  will throw ValueError.

Converting number to string

To convert number  to string  you need to use str()  function.

Rounding numbers

To round numbers you need to use round()  function.

Syntax: round(number[, ndigits])

Next we will cover control statements.


Other Tutorials

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Leave a Reply

7 Comments on "Datatype conversion"

Notify of
avatar
Sort by:   newest | oldest | most voted
vishal
Guest

hey admin,
there might be something wrong in first example. You are using i=10 for input, and after conversion from int to float, it’s showing 14.0

xexanos
Guest

Hey,
in your first example you write “To convert float to int” but it should be “To convert int to float”.

Alex Makhalane
Guest

Hi Admin

1. Converting Number to String does not work. The following error is displayed:

“Traceback (most recent call last):
File “”, line 1, in
TypeError: ‘str’ object is not callable”

2. Rounding Numbers rounds off to 2 decimal places regardless of the number in the second parameter.

round(i, 2), round(i, 3), round(i, 4) etc. all result in 24.0

I am using Python 3.9.3 (v3.6.3:2c5fed8)

Regards

Alex Makhalane
Guest

Sorry, I meant Python 3.6.3.

Jacob
Guest

Here is how to convert number to string.


>>>
>>> str(3.14)
'3.14'
>>> str(100)
'100'
>>>

Secondly, if you are not getting the required result using round() function, try format() function.