Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round up or down to closest 20

As the question suggests, I need to round up or down to closest 20, with the exception of numbers from 0-14, all must round to 20, because no zero values are allowed.The table has not to be updated with new values.For now I have managed only rounding up or down to the nearest 100 as seen below:

 CASE WHEN ROUND(number,-2)=0 THEN CAST(ROUND(number,-2)+100 AS DECIMAL(18, 0)) 
      ELSE CAST(ROUND(number,-2) AS DECIMAL(18,0)) END AS [NUMBER]
like image 909
Hari Avatar asked Dec 22 '11 14:12

Hari


2 Answers

Try this:

DECLARE @testValue Int = 35;

SELECT
  CASE
    WHEN @testValue BETWEEN 0 AND 14 THEN 20
    ELSE ROUND((@testValue * 1.0) / 20, 0) * 20
  END MyRoundedValue;

There may be a more optimal approach, but this was the first solution that came to mind. The * 1.0 is to force conversion to a floating point number so that the / 20 will produce fractional results. The result is rounded using ROUND then multiplied back by 20 to get your final "rounded" value.

Edited to take your special case of 0-14 into account...

like image 110
Yuck Avatar answered Oct 27 '22 07:10

Yuck


This will work:

--N = Your nearest number
--X = Number to round
SELECT ROUND(X/N, 0) * N

Example Usage:

DECLARE @numberToRound INT;
SET @numberToRound = 25;

CASE WHEN @numberToRound BETWEEN 0 AND 14 THEN
    20
ELSE
    ROUND((CAST(@numberToRound AS DECIMAL) / 20.00), 0) * 20
END
like image 39
James Hill Avatar answered Oct 27 '22 06:10

James Hill