Type conversion. Pascal's Round and Trunc Functions

When working in Pascal with variables of different types, it is often necessary to deal with the fact that when compiling a program errors occur that indicate incorrect conversion of values. For example, you cannot set an integer variable to 5.9, as this will lead to a compilation error. In this case, we have to talk about using the Round and Trunc functions in Pascal, with which you can convert the types of arguments and then perform certain tasks with them.

trunc in pascal

Type Conversion Overview

Type conversion (conversion of values) is the process of converting the values ​​of one data type to another. Distinguish between explicit and implicit type conversion. The first is set directly by the developer using either language constructs or through the use of functions, and the second is independently executed by the interpreter or code compiler according to the rules announced in the standard of a programming language.

Type Conversion in Pascal

In the Pascal programming language, you can use both explicit and implicit type conversions.

When explicitly casting types, Pascal uses calls to special conversion functions whose arguments belong to the same type and the value to a completely different data type. Those are the Trunc function in Pascal and the Round function, which will be discussed in more detail below.

Implicit type casting in this language is possible only in those cases when in expressions that consist of integer and real variables, the first are automatically converted to the second type.

Next, we will talk about how you can implement type casting for numeric data.

trunc function in pascal

Trunc

Built-in math function. Trunc in Pascal discards the entire fractional part of the argument, leading it to an integer form. For example, by calling a function Trunc with argument (1.73) in the end, you can get the result 1.

Syntax features : Trunc (x: real): Longint.

Round

Built-in math function. The Round function rounds the argument according to the rules of mathematics to the nearest integer. For example, calling Round (1.73) will end up with 2, and Round from argument (1.11) will give 1.

Function Syntax : Round (x: real): Longint.

It is worth noting that there are limitations to the result of executing the Round and Trunc functions in Pascal. Execution will fail if this result goes beyond Longint type values.

Obviously, the syntax of both built-in functions is quite simple and allows you to use Round and Trunc in Pascal to explicitly convert types without unnecessary troubles and does not cause compilation errors about type violation.


All Articles