how to round the given number to the nearest 0.25

Posted by Admin on 14-Jun-2011 06:03

how to round the given number to the nearest 0.25?

Help urgent.

All Replies

Posted by Matt Baker on 14-Jun-2011 08:45

.25 is just 25 with a different factor of 10.  So multiply your number by 100 and either round or truncate the result to two decimals (you could scale it higher if you have more than 2 decimals)  Subtract the modulos, and then divide by your scale (100).  This really is truncation not rounding.  If you need true rounding then test the modulus.  If less than 15 then subtract the modules.  If more than 15, then add the difference between 25 and the modulo.  Then divide by the scale (100) to return the decimals.

function round25 returns decimal 

    (input original as decimal,
     input scale as integer):
   
   
    define variable scaled as integer no-undo.
   
    scaled = integer (original * scale).
   
/*    display scaled. */
   
    define variable modd as integer no-undo.
   
    modd = scaled modulo 25.
   
/*    display modd. */
   
    define variable result as decimal no-undo.
   
    result = (scaled - modd) / scale.
   
/*    display result. */
   
    return result.

end function.


display round25 (100.99, 100).

Posted by Shrog on 30-Jun-2011 02:27

There is a much simpler solution. Multiply by 4, round to the nearest whole number, then divide by 4.

You can write it in one line:

    Answer = INT(MyNumber * 4) / 4.

You can of course divide and multiply by 0.25 instead of multiplying and dividing by 4:

    Answer = 0.25 * INT(MyNumber / 0.25).

Or use this little function:

FUNCTION RoundToNearest RETURNS DECIMAL
  (INPUT pdNumber  AS DECIMAL,
   INPUT pdNearest AS DECIMAL ) :

   RETURN pdNearest * INTEGER(pdNumber / pdNearest).

END FUNCTION.

This function will work with anything, rounding to the nearest 0.25, the nearest 25, the nearest 1000 and even the nearest 13.67, if you were that way inclined.

This thread is closed