What is Type Casting?
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:
Runnable example
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)let x = 5; // number
let y = 2.0; // number
let z = x + y; // no problem, result is a number
console.log(z);int x = 5;
double y = 2.0;
double z = x + y; // int promoted to double
System.out.println(z);int x = 5;
double y = 2.0;
double z = x + y; // int promoted to double
cout << z;Explicit casting is when you convert the type yourself:
Different languages do this in different ways:
- Python and JavaScript use functions like float() or Number() .
- 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)let x = 5;
let y = Number(x); // explicit casting with function
console.log(y);int x = 5;
double y = (double) x; // explicit casting with (type)
System.out.println(y);int x = 5;
double y = (double) x; // explicit casting with (type)
cout << 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:
Runnable example
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))