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
Alex Makhalane
Guest
Alex Makhalane
29 days 36 minutes ago

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

Jacob
Guest
Jacob
28 days 19 hours ago

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.

Alex Makhalane
Guest
Alex Makhalane
29 days 35 minutes ago

Sorry, I meant Python 3.6.3.

xexanos
Guest
xexanos
2 years 1 month ago

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

vishal
Guest
vishal
2 years 2 months ago

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

wpDiscuz