Type casting

 What is type casting?

Sometimes, it is necessary for us to convert from one data type to another. This is done by type casting.


Three built-in functions for type casting

1. int() 

2. float()

3. str()


Details

The int() function takes in a float and converts it into an integer. As an example, we will do int(2.36345) and it will give us 2. Anything after the decimal point is removed. To change a string into an integer, we will do int("6") and it will give us 6. However, we cannot type int("Hello") or int("2.36345"). There will be an error in both cases.


The float() function takes in an appropriate string or an integer to convert it into a float. As an example, we can type float("4.34") and it will give us 4.34 as it is now not a string because of the quotation marks being removed. Another example is that we can type in float(3) or float("3") and it will give 3.0.


The str() function converts an integer or float into a string. As an example, if we write str(5.3) we will get "5.3".

No comments:

Post a Comment