## C++ || Snippet – Round A Number To The Nearest Whole Number

This page will display a simple implementation of a function which rounds a floating point number to the nearest whole number. So for example, if the number 12.34542 was sent to the function, it would return the rounded value of 12.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```Modf - Modulus For Float Data How To Round A Number ```

``` Round A Number To The Nearest Whole Number C++ #include <iostream> #include <cmath> using namespace std; // function prototype double RoundNumber(double floatNumber); int main() { // declare variables double floatNumber = 0; cout<<"Enter in a floating point number to round: "; cin >> floatNumber; cout<<endl<<floatNumber<<" rounded to the nearest " "whole number is: "<< RoundNumber(floatNumber)<<endl; return 0; } double RoundNumber(double floatNumber) { // declare variables double intNumber = 0; // perform modulus (floatNumber % intNumber) // to render the decimal portion of the floatNumber double fraction = modf(floatNumber,&intNumber); // we round up if fraction >=.50 if(fraction >=.50) { ++intNumber; } return intNumber; }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637 #include <iostream>#include <cmath>using namespace std; // function prototypedouble RoundNumber(double floatNumber); int main(){ // declare variables double floatNumber = 0; cout<<"Enter in a floating point number to round: "; cin >> floatNumber;  cout<<endl<<floatNumber<<" rounded to the nearest " "whole number is: "<< RoundNumber(floatNumber)<<endl;  return 0;} double RoundNumber(double floatNumber){ // declare variables double intNumber = 0;  // perform modulus (floatNumber % intNumber) // to render the decimal portion of the floatNumber double fraction = modf(floatNumber,&intNumber);  // we round up if fraction >=.50 if(fraction >=.50) { ++intNumber; } return intNumber;}// 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.

Once compiled, you should get this as your output
(Note: the code was compile three separate times to display different output)

`====== RUN 1 ======`

``` Enter in a floating point number to round: 1.3333 1.3333 rounded to the nearest whole number is: 1 ====== RUN 2 ====== Enter in a floating point number to round: 35.56 35.56 rounded to the nearest whole number is: 36 ====== RUN 3 ====== Enter in a floating point number to round: 19.8728 ```

```19.8728 rounded to the nearest whole number is: 20 ```