# Rounding up

Hi, im having a problem with rouding up a number. A servo engine is moving back and forth between 0-180 degrees. I want to divide that to ten sections. So something like this:

17/18=0.944444444444444 and 142/18=7.888888888888888

I want to round up the answer to its closest “whole number”, i understand that i can make a long If statement but are hoping there is a easier way.

Regards // Tobi

The same way you always round up - add a half and truncate.

Using integer math only, as if the values are in char, int or long variables;

division
17 / 18 = 0 0 is the quotient

remainder
17 % 18 = 17

is remainder half or more of the dividend (18)?
if ( 17 > ( 18 / 2 ))
{
// add one to the quotient
}

Please avoid using floats on Arduino. The precision is low, when you calculate with floats you lose accuracy so much of the time (search words 'floating point sand dirt' if you to know more) where using integers and small units (or fixed-point math) you at least know how many places you are good to (more than float, with 64-bit type long long, 19 places accurate) and....
32 bit integer ops (good to 9 places) run about 100x faster than floats.

Just add half the divisor (9, in this case) to the dividend, then do the division.

x = (a + b / 2) / b;

<==>

x = (a2 + b) / (b2); // less divisions is faster - OK range is less

Take a look at floor() and ceil().

tobbee89:
Hi, im having a problem with rouding up a number. A servo engine is moving back and forth between 0-180 degrees. I want to divide that to ten sections. So something like this:

17/18=0.944444444444444 and 142/18=7.888888888888888

I want to round up the answer to its closest "whole number", i understand that i can make a long If statement but are hoping there is a easier way.

Regards // Tobi

Just scale it down and multiply by the scale.

scaledAngle = inputAngle / 18 * 18;

Example: 43 degrees / 18 = 2. Then 2*18 = 36 degrees. That will give you stops at 0, 18, 36... 180 degrees.