⬅ Previous Topic
Type Systems - Static vs Dynamic TypingNext Topic ⮕
Arithmetic Operators⬅ Previous Topic
Type Systems - Static vs Dynamic TypingNext Topic ⮕
Arithmetic OperatorsType 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.
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 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
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 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
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.
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
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
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
⬅ Previous Topic
Type Systems - Static vs Dynamic TypingNext Topic ⮕
Arithmetic OperatorsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.