# Examples of rounding and truncating floating point values in C Plus Plus

C++ (C Plus Plus) provides built-in functions for truncating and rounding floating point data items. The *ceil *function calculates the next highest integer value for a given floating point value. The *floor *function calculates the next lowest integer value for a given floating point number.

ceil(x) returns the smallest integer not less than x.

floor(x) returns the largest integer not greater than x.

if x is a whole number, then ceil(x) and floor(x) both return x.

For example...

ceil(1.1) returns the integer 2.

floor(1.1) returns the integer 1.

The example code, below, is targeted for Microsoft C++ in Microsoft Visual Studio.

## Examples of rounding and truncating floating point values in C Plus Plus

//**************************************************************************************** // ceil and floor.cpp * // Examples of rounding and truncating floating point values in C++ * // Author: nicomp * // * //**************************************************************************************** #include <iostream> #include <math.h> using namespace std; void main() { double rounded = 0; double num = .5; cout << "\n ceil(" << num << ") " << ceil(num); cout << "\n floor(" << num << ") " << floor(num); if (num - floor(num) >= .5) rounded = floor(num + 1); else rounded = floor(num); cout << "\n " << num << " rounds to " << rounded; num = .4999; cout << "\n ceil(" << num << ") " << ceil(num); cout << "\n floor(" << num << ") " << floor(num); if (num - floor(num) >= .5) rounded = floor(num + 1); else rounded = floor(num); cout << "\n " << num << " rounds to " << rounded; num = .50001; cout << "\n ceil(" << num << ") " << ceil(num); cout << "\n floor(" << num << ") " << floor(num); if (num - floor(num) >= .5) rounded = floor(num + 1); else rounded = floor(num); cout << "\n " << num << " rounds to " << rounded; num = .51; cout << "\n ceil(" << num << ") " << ceil(num); cout << "\n floor(" << num << ") " << floor(num); if (num - floor(num) >= .5) rounded = floor(num + 1); else rounded = floor(num); cout << "\n " << num << " rounds to " << rounded; num = .99; cout << "\n ceil(" << num << ") " << ceil(num); cout << "\n floor(" << num << ") " << floor(num); if (num - floor(num) >= .5) rounded = floor(num + 1); else rounded = floor(num); cout << "\n " << num << " rounds to " << rounded << "\n"; }

5