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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With