C++ || How To Round A Number To The Nearest X Using C++

The following is a module with functions which demonstrates how to round a number to the nearest X using C++.

This function has the ability to either round a number to the nearest amount, always round up, or always round down. For example, when dealing with money, this is good for rounding a dollar amount to the nearest 5 cents.

This function can be used to round a number up or down by any step amount.


1. Round – Nearest

The example below demonstrates the use of ‘Utils::roundAmount‘ to round a number to the nearest 5 cents.

The optional function parameter determines they type of rounding to perform.


2. Round – Up

The example below demonstrates the use of ‘Utils::roundAmount‘ to always round a number up to the nearest 5 cents.

The optional function parameter determines they type of rounding to perform.


3. Round – Down

The example below demonstrates the use of ‘Utils::roundAmount‘ to always round a number down to the nearest 5 cents.

The optional function parameter determines they type of rounding to perform.


4. Utils Namespace

The following is the Utils Namespace. Include this in your project to start using!


5. More Examples

Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Was this article helpful?
👍 YesNo

Leave a Reply