C++ Nearest Integer Functions

beginner c++11 math

#include <cmath>

The C++ Standard Library provides the ceil, floor, trunc, and round series of functions which all take a single floating point argument and return nearby integers.

Ceil

The ceil function returns the smallest integer that is not less than its argument.

#include <cmath>
#include <iostream>

int main() {
  auto ceiling = std::ceil(3.141592f);

  std::cout << ceiling << "\n";
  
  ceiling = std::ceil(-3.141592f);

  std::cout << ceiling << "\n";
}
4
-3

Floor

The floor function returns the largest integer that is not greater than its argument.

#include <cmath>
#include <iostream>

int main() {
  auto floor = std::floor(3.141592f);

  std::cout << floor << "\n";
  
  floor = std::floor(-3.141592f);

  std::cout << floor << "\n";
}
3
-4

Trunc

The trunc function returns the nearest integer to its argument by removing the decimal portion of the argument.

#include <cmath>
#include <iostream>

int main() {
  auto trunc = std::trunc(3.141592f);

  std::cout << trunc << "\n";
  
  trunc = std::trunc(-3.141592f);

  std::cout << trunc << "\n";
}
3
-3

Truncation is also what happens when you assign a floating point value to an integer value in C++.

#include <cmath>
#include <iostream>

int main() {
  float pi = 3.141592f;

  int trunc = pi;

  std::cout << trunc << "\n";
  
  trunc = -pi;

  std::cout << trunc << "\n";
}
3
-3

Round

The round function returns the nearest integer to its argument. When the argument is halfway between two integers (.5) the value is rounded away from zero.

#include <cmath>
#include <iostream>

int main() {
  auto round = std::round(3.141592f);

  std::cout << round << "\n";
  
  round = std::round(3.5f);

  std::cout << round << "\n";
  
  round = std::round(-3.5f);

  std::cout << round << "\n";
}
3
4
-4

For more C++ By Example, click here.