C++ Math trunc
The function truncates the provided value towards zero and outputs the closest whole number whose absolute value is less than or equal to the given value.
For example:
trunc(3.8) = 3;
Syntax
Suppose a number is 'x'. Syntax would be :
return_type trunc(data_type x);
Note: return_type can be float,double or long double.
Parameter
x : The value can be of type float, double, or long double.
Return value
It returns a rounded value of x.
Example 1
Let's examine a basic scenario where the value of x is greater than zero.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
float x=8.8;
std::cout << "The value of x is :" <<x<< std::endl;
std::cout << "Truncated value of x is :" <<trunc(x)<< std::endl;
return 0;
}
Output:
The value of x is :8.8
Truncated value of x is :8
Example 2
Let's examine a basic scenario where x holds a negative value.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
double x=-3.9;
std::cout << "The value of x is :" <<x<< std::endl;
std::cout << "Truncated value of x is:" <<trunc(x)<< std::endl;
return 0;
}
Output:
The value of x is :-3.9
Truncated value of x is:-3