03-20-2006, 06:19 AM
Quote:Let's not forget that positive numbers are rounded UP using .5, and negative numbers are rounded DOWN using -.5.
So, the simplest way is to test the sign of the number to be rounded, and set the rounding factor to .5 or -.5 accordingly. Something like this:*****Code:IF NUMBER < 0 THEN RFACTOR=-.5 ELSE RFACTOR=.5
RESULT=INT(NUMBER+RFACTOR)
Hey guys, about a year after posting the above rounding solution, I discovered that using a rounding factor of .5 or -.5 does not work 100% for reasons unknown.
However, during this time, I discovered a foolproof rounding algorithm by Oracle, which is described in detail in this extract from a tutorial I wrote for QBNZ. Sorry I didn't correct this old post sooner. See the one line rounding algorithm at the end.
6. ROUNDING NUMBERS (POSITIVE OR NEGATIVE):
CREDIT: Oracle of Qbasicnews and QBNZ.
The purpose is to round positive or negative numbers to the nearest whole
number. The standard convention of "half-adjusting" by a rounding factor of
.5 is used. Notice that positive numbers must be rounded up, and negative
numbers are rounded down, that is, to a greater negative number.
NOTE: If you do INT(123.9) you will get 123. However, if you do INT(-123.9)
you will get -124. This is the documented method of how the INT works
in QB, which in the case of the INT(-123.9), is NOT what we want,
since we want -123.
The following code takes the above conditions into consideration.
* The absolute or ABS assures that the number to work with is positive.
* This positive number is rounded by the rounding factor of "+.5".
* The integer value INT is taken on the above positive result.
* The sign of the original input number is restored by multiplying by the
sign or SGN which is 1 for positive, -1 for negative, and 0 for zero.
GIVEN:
* N is the number to be rounded. Obviously, since it can have decimals,
it must have a type declaration of single or double floating point.
We will define it as single (!) for this example.
* R will be the resultant rounded whole number.
R = SGN(N!) * INT(ABS(N!) + .5)
*****