## 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.

``` 1. Round - Nearest C++ // Round - Nearest // Declare values to round double values[] = { 19.28, 31.22, 19.91, 19.87, 0.05 }; // Declare step amount double stepAmount = 0.05; // Round to nearest amount for (const auto& value : values) { std::cout << "Value: " << value << ", Rounded: " << Utils::roundAmount(value, stepAmount) << std::endl; } // expected output: /* Value: 19.28, Rounded: 19.3 Value: 31.22, Rounded: 31.2 Value: 19.91, Rounded: 19.9 Value: 19.87, Rounded: 19.85 Value: 0.05, Rounded: 0.05 */ 12345678910111213141516171819202122 // Round - Nearest // Declare values to rounddouble values[] = { 19.28, 31.22, 19.91, 19.87, 0.05 }; // Declare step amountdouble stepAmount = 0.05; // Round to nearest amountfor (const auto& value : values) {    std::cout << "Value: " << value << ", Rounded: "         << Utils::roundAmount(value, stepAmount) << std::endl;} // expected output:/*    Value: 19.28, Rounded: 19.3    Value: 31.22, Rounded: 31.2    Value: 19.91, Rounded: 19.9    Value: 19.87, Rounded: 19.85    Value: 0.05, Rounded: 0.05*/ ```

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.

``` 2. Round - Up C++ // Round - Up // Declare values to round double values[] = { 19.28, 31.22, 19.91, 19.87, 0.05 }; // Declare step amount double stepAmount = 0.05; // Round up to nearest amount for (const auto& value : values) { std::cout << "Value: " << value << ", Rounded: " << Utils::roundAmount(value, stepAmount, Utils::RoundType::Up) << std::endl; } // expected output: /* Value: 19.28, Rounded: 19.3 Value: 31.22, Rounded: 31.25 Value: 19.91, Rounded: 19.95 Value: 19.87, Rounded: 19.9 Value: 0.05, Rounded: 0.05 */ 12345678910111213141516171819202122 // Round - Up // Declare values to rounddouble values[] = { 19.28, 31.22, 19.91, 19.87, 0.05 }; // Declare step amountdouble stepAmount = 0.05; // Round up to nearest amountfor (const auto& value : values) {    std::cout << "Value: " << value << ", Rounded: "        << Utils::roundAmount(value, stepAmount, Utils::RoundType::Up) << std::endl;} // expected output:/*    Value: 19.28, Rounded: 19.3    Value: 31.22, Rounded: 31.25    Value: 19.91, Rounded: 19.95    Value: 19.87, Rounded: 19.9    Value: 0.05, Rounded: 0.05*/ ```

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.

``` 3. Round - Down C++ // Round - Down // Declare values to round double values[] = { 19.28, 31.22, 19.91, 19.87, 0.05 }; // Declare step amount double stepAmount = 0.05; // Round down to nearest amount for (const auto& value : values) { std::cout << "Value: " << value << ", Rounded: " << Utils::roundAmount(value, stepAmount, Utils::RoundType::Down) << std::endl; } // expected output: /* Value: 19.28, Rounded: 19.25 Value: 31.22, Rounded: 31.2 Value: 19.91, Rounded: 19.9 Value: 19.87, Rounded: 19.85 Value: 0.05, Rounded: 0.05 */ 12345678910111213141516171819202122 // Round - Down  // Declare values to rounddouble values[] = { 19.28, 31.22, 19.91, 19.87, 0.05 }; // Declare step amountdouble stepAmount = 0.05; // Round down to nearest amountfor (const auto& value : values) {    std::cout << "Value: " << value << ", Rounded: "        << Utils::roundAmount(value, stepAmount, Utils::RoundType::Down) << std::endl;} // expected output:/*    Value: 19.28, Rounded: 19.25    Value: 31.22, Rounded: 31.2    Value: 19.91, Rounded: 19.9    Value: 19.87, Rounded: 19.85    Value: 0.05, Rounded: 0.05*/ ```

4. Utils Namespace

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

``` Utils Namespace C++ // ============================================================================ // Author: Kenneth Perkins // Date: Feb 25, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.h // Description: Handles general utility functions // ============================================================================ #pragma once #include <cmath> #include <stdexcept> #include <string> namespace Utils { enum RoundType { Nearest, Up, Down }; /** * FUNCTION: roundAmount * USE: Rounds a number to the nearest X * @param value: The value to round * @param stepAmount: The amount to round the value by * @param type: The type of rounding to perform * @return: The value rounded by the step amount and type */ double roundAmount(double value, double stepAmount, RoundType type = RoundType::Nearest) { double inverse = 1 / stepAmount; double dividend = value * inverse; switch (type) { case RoundType::Nearest: dividend = std::round(dividend); break; case RoundType::Up: dividend = std::ceil(dividend); break; case RoundType::Down: dividend = std::floor(dividend); break; default: throw std::invalid_argument{ "Unknown type: '" + std::to_string(type) + "'" }; break; } double result = dividend / inverse; return result; } }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 // ============================================================================//    Author: Kenneth Perkins//    Date:   Feb 25, 2021//    Taken From: http://programmingnotes.org///    File:  Utils.h//    Description: Handles general utility functions// ============================================================================#pragma once#include <cmath>#include <stdexcept>#include <string> namespace Utils {    enum RoundType {        Nearest,        Up,        Down    };     /**    * FUNCTION: roundAmount     * USE: Rounds a number to the nearest X    * @param value: The value to round    * @param stepAmount: The amount to round the value by    * @param type: The type of rounding to perform    * @return: The value rounded by the step amount and type    */    double roundAmount(double value, double stepAmount, RoundType type = RoundType::Nearest) {        double inverse = 1 / stepAmount;        double dividend = value * inverse;        switch (type) {            case RoundType::Nearest:                dividend = std::round(dividend);                break;            case RoundType::Up:                dividend = std::ceil(dividend);                break;            case RoundType::Down:                dividend = std::floor(dividend);                break;            default:                throw std::invalid_argument{ "Unknown type: '" + std::to_string(type) + "'" };                break;        }        double result = dividend / inverse;        return result;    }}// http://programmingnotes.org/ ```

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!

``` More Examples C++ // ============================================================================ // Author: Kenneth Perkins // Date: Feb 25, 2021 // Taken From: http://programmingnotes.org/ // File: program.cpp // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ #include <iostream> #include <string> #include <exception> #include "Utils.h" void display(const std::string& message); int main() { try { // Declare values to round double values[] = { 19.28, 31.22, 19.91, 19.87, 0.05 }; // Declare step amount double stepAmount = 0.05; // Round to nearest amount for (const auto& value : values) { std::cout << "Value: " << value << ", Rounded: " << Utils::roundAmount(value, stepAmount) << std::endl; } display(""); // Round up to nearest amount for (const auto& value : values) { std::cout << "Value: " << value << ", Rounded: " << Utils::roundAmount(value, stepAmount, Utils::RoundType::Up) << std::endl; } display(""); // Round down to nearest amount for (const auto& value : values) { std::cout << "Value: " << value << ", Rounded: " << Utils::roundAmount(value, stepAmount, Utils::RoundType::Down) << std::endl; } } catch (std::exception& e) { display("\nAn error occurred: " + std::string(e.what())); } std::cin.get(); return 0; } void display(const std::string& message) { std::cout << message << std::endl; }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 // ============================================================================//    Author: Kenneth Perkins//    Date:   Feb 25, 2021//    Taken From: http://programmingnotes.org///    File:  program.cpp//    Description: The following demonstrates the use of the Utils Namespace// ============================================================================#include <iostream>#include <string>#include <exception>#include "Utils.h" void display(const std::string& message); int main() {    try {        // Declare values to round        double values[] = { 19.28, 31.22, 19.91, 19.87, 0.05 };         // Declare step amount        double stepAmount = 0.05;         // Round to nearest amount        for (const auto& value : values) {            std::cout << "Value: " << value << ", Rounded: "                 << Utils::roundAmount(value, stepAmount) << std::endl;        }         display("");         // Round up to nearest amount        for (const auto& value : values) {            std::cout << "Value: " << value << ", Rounded: "                << Utils::roundAmount(value, stepAmount, Utils::RoundType::Up) << std::endl;        }         display("");         // Round down to nearest amount        for (const auto& value : values) {            std::cout << "Value: " << value << ", Rounded: "                << Utils::roundAmount(value, stepAmount, Utils::RoundType::Down) << std::endl;        }    } catch (std::exception& e) {        display("\nAn error occurred: " + std::string(e.what()));    }     std::cin.get();    return 0;} void display(const std::string& message) {    std::cout << message << std::endl;}// http://programmingnotes.org/ ```

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.