Type Conversion

Type conversion is the process of changing a value from one data type to another. Programs often need to do this because different types serve different purposes and don’t always mix freely — you can multiply two integers, but you can’t multiply a string and an integer.

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.

int score = 42;
double result = score;

Converting an int to a double is always safe — a double can represent any integer value — so the language handles it silently.

score = 42
result = score + 0.0

Python automatically promotes the integer to a float when mixed with a float value.

let score = 42;
let result = score + 0.0;

JavaScript automatically promotes the integer to a float when mixed with a float value.

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.

double price = 9.99;
int rounded = (int)price;

rounded will be 9, not 10. The decimal part is simply dropped, not rounded. Because data can be lost, you must write the conversion explicitly.

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.

Parsing#

A specific and very common kind of explicit conversion is parsing — converting a string into another type by reading its content. This comes up whenever a program receives input from the user, which always arrives as text.

See Parsing for a full explanation and examples.

Common Mistakes#

Expecting implicit conversion where it doesn’t exist Not all languages convert automatically between all types. In C#, assigning a double to an int variable without an explicit cast is a compile error. Don’t assume the language will handle it.

Confusing truncation with rounding Converting 9.99 to an integer gives 9, not 10. Explicit conversion truncates — it drops the decimal part entirely. Use a rounding function if you need the nearest integer.

Assuming string-to-number conversion is automatic In most languages, "1" + 1 does not give 2. The string must be parsed explicitly before arithmetic will work correctly.

Losing data silently Explicit conversions that drop data — like double to int — do so without warning. Always check whether the lost precision matters for your use case.

Resources#