What is the difference between Math.Floor() and Math.Truncate() in c

1 Answer

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

/*
Math.Floor(x)
    Rounds down toward −∞ (negative infinity)
    Always goes to the next lower integer

Math.Truncate(x)
    Removes the fractional part
    Rounds toward zero (up)
*/

/*
Use Math.Floor() when:
    * You want “round down” in the mathematical sense
    * You’re computing ranges, bins, or intervals
    * You want consistent behavior for negative values

Use Math.Truncate() when:
    * You want to simply drop decimals
    * You want symmetric behavior around zero
    * You’re converting to an integer-like value without rounding
*/

void test(double x) {
    double f = floor(x);
    double t = trunc(x);

    printf("x = %6.2f | floor = %6.2f | truncate = %6.2f\n", x, f, t);
}

int main()
{
    test(5.9);
    test(5.1);
    test(1.0);
    test(0.0);
    test(-0.1);
    test(-1.1);
    test(-5.1);
    test(-5.9);
    test(-10.0);

    return 0;
}


/*
run:

x =   5.90 | floor =   5.00 | truncate =   5.00
x =   5.10 | floor =   5.00 | truncate =   5.00
x =   1.00 | floor =   1.00 | truncate =   1.00
x =   0.00 | floor =   0.00 | truncate =   0.00
x =  -0.10 | floor =  -1.00 | truncate =  -0.00
x =  -1.10 | floor =  -2.00 | truncate =  -1.00
x =  -5.10 | floor =  -6.00 | truncate =  -5.00
x =  -5.90 | floor =  -6.00 | truncate =  -5.00
x = -10.00 | floor = -10.00 | truncate = -10.00

*/

 



answered Apr 13 by avibootz

Related questions

1 answer 100 views
1 answer 116 views
1 answer 133 views
1 answer 112 views
1 answer 89 views
...