Math Trunc Function - C++ Programming Tutorial
C++ Course / Math Functions / Math Trunc Function

Math Trunc Function

BLUF: Mastering Math Trunc Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Math Trunc Function

C++ is renowned for its efficiency. Learn how Math Trunc Function enables low-level control and high-performance computing in the tutorial below.

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:

Example

trunc(3.8) = 3;

Syntax

Suppose a number is 'x'. Syntax would be :

Example

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.

Example

#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:

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.

Example

#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:

Output

The value of x is :-3.9
Truncated value of x is:-3

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience