Skip to main content

Section 4.10 Rounding Functions

At this point, you should take a minutes to scan the list of functions offered in the cmath library. You do not need to memorize them, but it is useful to be aware of what is there so you can go look up the exact syntax when you need to do some math.
Notice that the functions are listed in categories. One of the categories is named Nearest integer floating-point operations, which is a long-winded way of saying β€œrounding”.
If you have a floating-point value and want to convert it to a whole number, one way you can do so is to cast it into an int. But that always drops the decimal portion. So something like 7.9999 will become 7. Often times, what you want to do is to round to the nearest integer value (8). Other times, you might want to round up to the next nearest value β€” if you calculate that a print job takes 7.2 pages, the actual number of pages printed will be 8.
For rounding in this way, the cmath library provides these rounding functions: floor, ceil , round, and trunc:
floor
rounds down to the nearest whole number
ceil
rounds up to the next nearest integer
round
rounds to the nearest integer
trunc
truncates (removes) the decimal part of the number
The following program demonstrates their use:
Listing 4.10.1.
When you run this program, you will see that floor rounds down to the nearest whole number, ceil rounds up to the nearest whole number, round rounds to the nearest whole number, and trunc truncates the decimal part of the number. Experiment with different test values to see how they are rounded.
If you look at the documentation for the round function (or any of the others), you will see that despite the output being a whole number, it is returned as a double. This makes it easy to continue doing more floating-point calculations with the value. But it means that to store the result as an int, you need to cast the result:
double rounded = round(7.2);
int roundedInt = static_cast<int>(rounded);

// or in one line:
int roundedInt = static_cast<int>( round(7.2) );
You also may notice that round only rounds to the nearest whole number. But you can use it to round to a specific number of decimal places by multiplying the original number by a power of 10 to shift the digits, then rounding, and then dividing by the same number to shift the digits back. For example, to round to two decimal places, you can multiply by 100 to shift the decimal point over 2 digits, round, and then divide by 100 to move the decimal point back:
Listing 4.10.2.

Checkpoint 4.10.1.

You have attempted of activities on this page.