# Thread: Rounding a float to the nearest half

1. ## Rounding a float to the nearest half

Hi again. I struck a bit of a problem with my program. I needed to take a number and then round it to the neerest half. After quite a while I finaly managed to hack it together but I was wondering if there is a cleaner way to do it?

Here is my bodged way of doing it:

Code:
```
float weight;
float remainder;
int whole;

weight = 11.24;

whole = weight / 1;
remainder = weight - whole;
if (remainder < 0.5)
if (remainder >= 0.25)
remainder = 0.5;
else
remainder = 0.0;
else
if (remainder >= 0.75)
remainder = 1.0;
else
remainder = 0.5;

weight = whole + remainder;```
Thanks

2. Originally Posted by kzar
Hi again. I struck a bit of a problem with my program. I needed to take a number and then round it to the neerest half.
You could consider this:

1. Multiply by 2.0
2. Round to nearest integer value.
3. Divide by 2.0

Regards,

Dave

3. Originally Posted by Dave Evans
You could consider this:

1. Multiply by 2.0
2. Round to nearest integer value.
3. Divide by 2.0

Regards,

Dave
Thanks that works great.

Code:
```    float weight;

weight = 11.75;
weight = round(weight * 2.0) / 2.0;```

4. don't forget that when converting from float ot int, the computer just chops off the decimal places - in effect rounding towards zero. To counter this, add 0.5 if its positive and subtract 0.5 if its negative before going from float to int.

To check this try putting in 11.8 and it will go to 11.5 if haven't done it.

5. Originally Posted by FlyingDutchMan
don't forget that when converting from float ot int, the computer just chops off the decimal places - in effect rounding towards zero. To counter this, add 0.5 if its positive and subtract 0.5 if its negative before going from float to int.

To check this try putting in 11.8 and it will go to 11.5 if haven't done it.

He said that this works:
Originally Posted by kzar
Code:
`   weight = round(weight * 2.0) / 2.0;`
Since he said it worked, I would assume he is using the C99 Standard library function round() or an equivalent home-grown round() function that does its job. If you have GNU gcc you can try it yourself. (Put in 11.8 and it goes to 12.0)

The library function round() doesn't covert float to int. It returns a double whose value is the rounded integer value of its argument.

Regards,

Dave