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

Print Friendly, PDF & Email

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


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

Was this article helpful?
👍 YesNo

Leave a Reply