Type casting (or type conversion) is the process of changing a value from one data type into another.
This is useful when you want to use a value in a calculation, but the value is stored as another type, like a text string.
For example, if we have the string "5" and the number 10, we cannot directly add them together. First we need to convert the string into a number:
a = "5"
b = 10
c = int(a) + b
print(c)Implicit vs Explicit Casting
There are two types of type casting:
- Implicit casting (also called type promotion) - done automatically by the programming language.
- Explicit casting - when the programmer converts the type manually.
For example, in many languages an integer can be automatically promoted to a float if needed:
x = 5 # int
y = 2.0 # float
z = x + y # int automatically becomes float
print(z)Explicit casting is when you convert the type yourself:
Different languages do this in different ways:
- Python and JavaScript use functions like
float()orNumber(). - Java and C++ often use parentheses with the type in front of the value, like
(double) x.
x = 5
y = float(x) # explicit casting with function
print(y)Note: Type casting rules can vary between programming languages. Always be careful when converting between types, because some conversions may lose information (for example, converting a float like 3.9 into an integer becomes 3).
Real-Life Example
Type casting is often needed when doing calculations. For example, when dividing two integers, you might want a decimal result instead of a whole number.
Here is a program that calculates the percentage of a user's score compared to the maximum score in a game. We cast the value to a decimal type to get an accurate result:
max_score = 500
user_score = 423
# Convert user_score to float to get a decimal result
percentage = float(user_score) / max_score * 100.0
print("User's percentage is", round(percentage, 2))
No comments:
Post a Comment