What is Type Conversion?
Type conversion is the process of changing a value from one data type to another. For example, converting a number to a string or a float to an integer.
Why Do We Need Type Conversion?
In programming, operations often involve different types. To ensure correctness, the program might automatically convert types (called implicit conversion), or we may need to do it manually (explicit casting).
Implicit Type Conversion (Type Coercion)
Implicit conversion is automatically done by the compiler/interpreter when it finds it safe and logical to do so. For example, converting an integer to a float in a mixed expression.
integer a = 5
float b = 4.2
float result = a + b // 'a' is implicitly converted to float
Output:
result = 9.2
Beginner Question:
Why doesn't the result stay an integer?
Because combining a float and an integer in arithmetic gives a more general type (float), to prevent loss of precision.
Explicit Type Casting (Manual Conversion)
Explicit casting is when you forcefully convert one type into another using a cast operator or function.
float price = 19.99
integer finalPrice = cast to integer(price)
Output:
finalPrice = 19
Beginner Question:
Why did the decimal part get removed?
Because converting from a float to an integer truncates the decimal — it doesn’t round, it just drops the fraction.
Common Use Case: String to Number
Reading input often gives us strings. To use them in arithmetic, we convert them explicitly.
string input = "42"
integer number = cast to integer(input)
integer result = number + 10
Output:
result = 52
Invalid Conversion Example
Not all conversions are safe. Trying to convert a non-numeric string to a number will result in an error.
string word = "hello"
integer value = cast to integer(word) // error
Output:
Error: cannot convert 'hello' to integer
Tips for Beginners
- Implicit conversions are automatic but may lead to unexpected results if you're not careful.
- Always check the type before casting, especially when reading from input or external sources.
- Converting to a narrower type (like float to int) can cause data loss.
Practice Intuition
Question: What happens when we convert a boolean true
to an integer?
Answer: Usually, true
becomes 1
and false
becomes 0
.
boolean isReady = true
integer status = cast to integer(isReady)
Output:
status = 1
Summary
- Implicit conversion is automatic and safe but may be hidden from the programmer.
- Explicit casting gives you full control and responsibility over conversions.
- Always be mindful of the data you're converting — not all values are safely castable.