Welcome
Welcome to the forums of AntiRTFM's Absolute N00b Spoonfeed C++ Tutorials!

You are currently viewing our boards as a guest, which gives you limited access to view most discussions and access our other features. By joining our free community, you will have access to post topics, communicate privately with other members (PM), respond to polls, upload content, and access many other special features. Registration is fast, simple, and absolutely free, so please, <a href="/profile.php?mode=register">join our community today</a>!

Rounding Numbers to Decimal Places

Display your little helpful snippets of code that may help us all get something done

Rounding Numbers to Decimal Places

Postby Adamp on Tue Jun 23, 2009 4:44 pm

Hi Again,

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;
}
Adamp
 
Posts: 14
Joined: Mon Jun 22, 2009 2:43 pm

Return to Snippets

Who is online

Users browsing this forum: No registered users and 0 guests