C++ trunc()

sudojarvis's avatar
Published Nov 10, 2022
Contribute to Docs

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

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
    • Beginner Friendly.
      11 hours

Syntax

std::trunc(x);

The x parameter is the value to be truncated.

The data type of the return value can be double, float, or long double.

Example

#include <iostream>
#include <cmath>
int main() {
double x = -3.14159;
double result;
result = std::trunc(x);
std::cout << "trunc(" << x << ") = " << result << "\n";
}

This will produce the following output:

trunc(-3.14159) = -3

Codebyte Example

The following example uses the trunc() function to round 12.3456 towards zero returning the value 12:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C++ on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
    • Beginner Friendly.
      11 hours