Problem with using Round function on even numbers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • santhosh p k

    Problem with using Round function on even numbers

    round function does not work properly with even number having decimal place .5. eg: Round(2.5)is 2 instead of 3.
  • code green
    Recognized Expert Top Contributor
    • Mar 2007
    • 1726

    #2
    Most languages seem to use bankers' rounding.
    This means midway values are rounded to the nearest even value.
    Code:
    So round(2.5) becomes 2.
    round(3.55,1) becomes 3.6
    To force a mid value always up, the trick is to add a constant EPSILON.
    This is an insignificant small value that won't throw out the sums but enough to trip rounding the right way.
    Code:
    round((qty * price) + EPSILON,2)
    The same technique is used when comparing floating point numbers
    2.5 == 5/2 may not return true, so instead compare the result to EPSILON.
    Code:
    if((2.5 - 5/2)) < EPSILON)
    So EPSILON is your tolerance. It should be smaller than the precision you will be displaying but slightly larger than the precision you are calculating.
    So if calculating in three decimal places, but displayng the result in two, EPSILON would be 0.001.

    Comment

    Working...