简体   繁体   中英

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]

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...

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

I prefer integer division * where possible, and if number is an integer, my solution would probably be something like this:

CASE
  WHEN number BETWEEN 0 AND 14 THEN 20  /* actually, it seems to make more sense
                                           to have the range as BETWEEN 0 AND 9,
                                           because values from 10 to 14 would be
                                           converted to 20 with the ELSE branch
                                           anyway */
  ELSE (number + 10) / 20 * 20
END

* SQL Server uses integer division when both operands are integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM