When I was making my currency converter, I needed a way to round my numbers to a specific number of decimal places (2). I made a simple function for that, but then I decided to make it more flexible and allow many different place values and rounding instructions so I could share it with everybody.
Here is my "Documentation":
Use roundDown and roundUp when you need to round your double value to a certain number of decimal places.
The first argument: num, is the value the function is going to round.
The second argument: places, is the number of decimal places the function is going to round your num value to. The value must be 0 or above.
The <cmath> header must be included.
Examples:
roundUp(4.7652, 2) = 4.77
roundDown(2.638278, 3) = 2.638
roundUp(27.4, 0) = 28
And here is the code with comments to assist in understanding:
- Code: Select all
//Be sure to include the <cmath> header or else your program won't compile.
#include <cmath>
//Place these declarations before the main() function or in a header that will be included in your program.
double roundUp(double num, unsigned int places);
double roundDown(double num, unsigned int places);
//Use this when you want to round your number up.
double roundUp(double num, unsigned int places)
{
double multiplier = (places != 0) ? pow(10.0, (double) places): 1;
return (ceil(num * multiplier)) / multiplier;
}
//Use this when you want to round your number up.
double roundDown(double num, unsigned int places)
{
double multiplier = (places != 0) ? pow(10.0, (double) places): 1;
return (floor(num * multiplier)) / multiplier;
}
