Type conversion is the process of changing a value from one type to another. Programs often need to do this because different types are used for different purposes, and they don’t always mix freely.
For example, you can multiply two integers, but you can’t multiply a string and an integer. If you have a value stored as the wrong type, you need to convert it first.
There are two kinds of type conversion: implicit and explicit.
Implicit Conversion#
An implicit conversion happens automatically, without you writing anything extra. The language does it for you when it knows the conversion is safe — meaning no data will be lost.
For example, converting an int to a double is always safe because a double can represent any integer value:
int score = 42;
double result = score;score = 42
result = score + 0.0let score = 42;
let result = score + 0.0;No data is lost, so the language handles it silently.
Explicit Conversion#
An explicit conversion is one you perform manually. It is required when the conversion could fail or lose data — so the language forces you to be deliberate about it.
For example, converting a double to an int loses the decimal part:
double price = 9.99;
int rounded = (int)price;rounded will be 9, not 10. The decimal part is simply dropped.
price = 9.99
rounded = int(price)rounded will be 9. The decimal part is simply dropped.
let price = 9.99;
let rounded = Math.trunc(price);rounded will be 9. The decimal part is simply dropped.
Because data can be lost, the language requires you to write the conversion explicitly. This makes the intention clear and prevents accidental mistakes.
Parsing#
A specific and common kind of explicit conversion is parsing: converting a string into another type by reading its content. This comes up often when a program receives input from the user, which always arrives as text.