C++ trunc()

The trunc() function in C++ rounds the argument towards zero and returns the nearest integral value that is not larger in magnitude than the argument.


trunc() prototype [As of C++ 11 standard]

double trunc(double x);
float trunc(float x);
long double trunc(long double x);
double trunc(T x); // For integral types

The trunc() function takes a single argument and returns a value of type double, float or long double type. This function is defined in <cmath> header file.

Note: To learn more about float and double in C++, visit C++ float and double.


trunc() Parameters

The trunc() function takes a single argument whose trunc value is to be computed.


trunc() Return value

The trunc() function rounds x towards zero and returns the nearest integral value that is not larger in magnitude than x.

Simply, the trunc() function truncate the value after decimal and returns the integer part only.


Example 1: How trunc() works in C++?

#include <iostream>
#include <cmath>
 
using namespace std;
 
int main()
{
    double x = 10.25, result;
    result = trunc(x);
    cout << "trunc(" << x << ") = " << result << endl;
 
    x = -34.251;
    result = trunc(x);
    cout << "trunc(" << x << ") = " << result << endl;
 
    return 0;
}

When you run the program, the output will be:

trunc(10.25) = 10
trunc(-34.251) = -34

Example 2: trunc() function for integral types

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int x = 15;
    double result;
    result = trunc(x);
    cout << "trunc(" << x << ") = " << result << endl;

    return 0;
}

When you run the program, the output will be:

trunc(15) = 15

For integral values, applying the trunc function returns the same value as a result. So it is not commonly used for integral values in practice.


Also Read:

Did you find this article helpful?