trunc() in C

trunc() rounds toward zero by discarding the fractional part. It returns a floating-point result.

Syntax Top ↑

double trunc(double x);

Example 1 Top ↑

#include <math.h>
#include <stdio.h>

int main(void) {
    double value = 5.89;

    printf("trunc(5.89): %.1f\\n", trunc(value));
    return 0;
}

Example 2 Top ↑

#include <math.h>
#include <stdio.h>

int main(void) {
    double value = -5.89;

    printf("trunc(-5.89): %.1f\\n", trunc(value));
    return 0;
}

Preserved trunc() Variations Top ↑

truncf() and truncl()

#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;
}

Truncate User Input

#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;
}

Truncate an Array of Values

#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;
}




plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer