Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to round a number?

Status
Not open for further replies.

WilliamGS

Programmer
Jan 21, 2004
54
PE
Hi all. Is there a way or function to round a number?. I am using VC++ 6.0

Thanks in advance.
William GS
 
Add 0.5 and cast to an int (and then back to double if you want).
Code:
double d1 = 1.3, d2 = 1.7;
double roundedDown = static_cast<int>(d1 + 0.5);
double roundedUp = static_cast<int>(d2 + 0.5);
// roundedDown = 1.0
// roundedUp = 2.0
 
Code:
double roundIt(double d)
{
  return static_cast<int>((d < 0.0) ? (d - 0.5) : (d + 0.5));
}
 
Code:
//! Rounding of \p v to the number of digit \p digit_count.
double round (double v, int digit_count = 0) 
{
  assert (digit_count >= 0);//positive_digit_count

  double dec_place = 1;
  for (int i = 1; i <= digit_count; i++)
    dec_place = dec_place * 10;

  int sign = v > 0 ? 1 : -1;
  double Result = (abs (v) * dec_place) + 0.5;
  int new_integer = (int) Result;
  Result = sign * (((double) new_integer) / dec_place);

  return Result;
}

--
Globos
 
Since a double only has 15 digits of precision, you don't need a whole int, a char is more than enough. You should be asserting if the abs(digit_count) is > 15.
This way a positive number might mean the number of digits to keep after the decimal point, or a negative number might mean the number of digits to round before the decimal place.

ex.
round( 3.14, 1 ) would return 3.1
round( 3.14, 0 ) would return 3.0
round( 3.50, -1 ) would return 4.0
round( 314, -2 ) would return 310

Also, instead of using abs() and casting to an int, you should use fabs() so that decimal numbers won't get lost.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top