trunc() rounds toward zero by discarding the fractional part. It returns a floating-point result.
double trunc(double x);#include <math.h>
#include <stdio.h>
int main(void) {
double value = 5.89;
printf("trunc(5.89): %.1f\\n", trunc(value));
return 0;
}#include <math.h>
#include <stdio.h>
int main(void) {
double value = -5.89;
printf("trunc(-5.89): %.1f\\n", trunc(value));
return 0;
}
#include <math.h>
#include <stdio.h>
int main(void) {
float f = -12.456f;
long double ld = 13.345L;
printf("truncf(%.3f) = %.1f\n", f, truncf(f));
printf("truncl(%.3Lf) = %.1Lf\n", ld, truncl(ld));
return 0;
}
#include <math.h>
#include <stdio.h>
int main(void) {
double value;
printf("Enter a number: ");
if (scanf("%lf", &value) != 1) {
printf("Invalid input.\n");
return 1;
}
printf("Truncated value: %.0f\n", trunc(value));
return 0;
}
#include <math.h>
#include <stdio.h>
int main(void) {
double values[] = {3.14, -2.73, 5.99, -7.01};
size_t count = sizeof values / sizeof values[0];
for (size_t i = 0; i < count; i++) {
printf("trunc(%.2f) = %.0f\n",
values[i], trunc(values[i]));
}
return 0;
}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.