HELP! - Rounding decimals

Hi, I am polishing up on my C++ and getting frustrated with this problem, would appreciate some help.

I need to enter a value eg 2.13 and return a rounded value with multiples of 0.5. So the answer should be 2.15 in this case.

Some of the rounding methods online are very confusing to me as i am just a beginner. Thanks in advance!
Since this is not a typical rounding issue you cannot use the rounding function.

You can use integer division:

1
2
3
4
5
int multiples_of_5 = int(x * 100) / 5; // Note: int(x * 100) simply truncates ther third digit
if((x * 100) > (multiples_of_5 * 5))
  return ((multiples_of_5 + 1) * 5);
else
  return (multiples_of_5 * 5);

Note: This is for positive numbers only!
Last edited on
It looks like you want to round to the nearest 0.05. That is 5/100 or 1/20. So, the process goes like this:

a. multiply by 20
b. round to nearest integer
c. divide by 20

1
2
3
4
double round05(double n)
{
    return  int(n * 20.0 + 0.5) / 20.0;
}

Took me some time to play around with the codes and finally got it to work.

Thanks guys!
Topic archived. No new replies allowed.