Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
trunc() , truncf() , truncl() in C language
In C, the trunc(), truncf(), and truncl() functions are used to truncate floating-point values, removing the fractional part and returning only the integer portion. These functions are part of the math.h library and are available in C99 and later standards.
Installation: These functions require C99 or later. Compile with
gcc -std=c99 -lmto link the math library.
Syntax
double trunc(double x); float truncf(float x); long double truncl(long double x);
Parameters
- x − The floating-point value to be truncated
Return Value
Returns the truncated value (integer part) as the same data type as the input parameter.
Example 1: Using trunc() Function
The trunc() function works with double type values ?
#include <stdio.h>
#include <math.h>
int main() {
double x = 53.26;
double y = -75.86;
double a = trunc(x);
double b = trunc(y);
printf("Original: %.2lf, Truncated: %.2lf<br>", x, a);
printf("Original: %.2lf, Truncated: %.2lf<br>", y, b);
return 0;
}
Original: 53.26, Truncated: 53.00 Original: -75.86, Truncated: -75.00
Example 2: Using truncf() Function
The truncf() function works with float type values ?
#include <stdio.h>
#include <math.h>
int main() {
float x = 53.26f;
float y = -75.86f;
float a = truncf(x);
float b = truncf(y);
printf("Original: %.2f, Truncated: %.2f<br>", x, a);
printf("Original: %.2f, Truncated: %.2f<br>", y, b);
return 0;
}
Original: 53.26, Truncated: 53.00 Original: -75.86, Truncated: -75.00
Example 3: Using truncl() Function
The truncl() function works with long double type values for higher precision ?
#include <stdio.h>
#include <math.h>
int main() {
long double x = 53547.55555555555L;
long double y = -78547.55555555523L;
long double a = truncl(x);
long double b = truncl(y);
printf("Original: %.5Lf, Truncated: %.5Lf<br>", x, a);
printf("Original: %.5Lf, Truncated: %.5Lf<br>", y, b);
return 0;
}
Original: 53547.55556, Truncated: 53547.00000 Original: -78547.55556, Truncated: -78547.00000
Key Points
- These functions always truncate towards zero (not towards negative infinity)
- For positive numbers:
trunc(3.7)returns3.0 - For negative numbers:
trunc(-3.7)returns-3.0 - The return type matches the input parameter type
Conclusion
The trunc() family functions provide a simple way to remove fractional parts from floating-point numbers. They work consistently across different data types and always truncate towards zero, making them useful for converting floating-point values to integers.
