Trunc
The Standard Pascal function trunc returns the integer part of a real-type value rounded toward zero.
trunc is short for “truncate”. The fraction part of the real value is, so to speak, cut off. However, unlike the int function the result is of integer type.
FPC implements this function as a compiler function.
definition
The mathematical definition reads as follows:
$\text{trunc}(x) := \begin{cases} \lfloor x \rfloor & \text{if } x \geq 0 \\ \lceil x \rceil & \text{if } x < 0 \end{cases}$
The function trunc is defined for all real values in the open interval (low(integer)-1, high(integer)+1). If the supplied parameter is out of range, a program compiled with FPC will stop with the run-time error 207 “Invalid floating point operation”. If the sysUtils is included, this RTE becomes the eInvalidOp exception.
application
Trunc is used to retrieve an integer value. It is primarily used where no loss in accuracy is expected if the fractional part (if any) is removed.
For example: Pascal does not have a power operator or function built in. Instead, one has to define their own function doing this task using already existing function. One can utilize the rule $a^x = e^{x \times \ln a}$ and the pre-existing exp and ln functions for that. However, if the operands are integers, it is guaranteed the result will be an integer to, yet exp will return a real value. The result can be truncated, without loss in precision. For source code, see [[*|asterisk § “exponentiation”]].
see also
- round
math.ceil– round upmath.floor– round down- frac – returns the fractional part of a floating point value
- int – returns the integer part of a floating point value
- div – integer division
- Comparison of approaches for rounding to an integer
From the Free Pascal wiki, page "Trunc", as it stood on 2020-05-23 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.
Talk about this page
Nobody has opened a bench for this page yet. Sign in to open one.
