Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round to the closest .25

Tags:

tsql

Does anyone know of a way to round to the closest .25 in t-sql? Currently I am rounding down using

floor(value * 4)/4

My client is changing their algorithm and wants to do a midpoint round to the closest quarter. If the value is less than .125 round to 0.00, if the value is greater than or equal to .125 round up to .25.

like image 315
Steve Salowitz Avatar asked Jan 28 '15 21:01

Steve Salowitz


3 Answers

I needed to round to an arbitrary precision & rounding strategy.

rounding to *.25

DECLARE @roundamt DECIMAL(16,2) = .25, @value DECIMAL(18, 2) = 1.7688
SELECT  ROUND(  (@value - FLOOR(@value)) / @roundamt, 0 ) * @roundamt + FLOOR(@value)

-- result = 1.750000

different rounding strategies like 0.02, 0.25, 0.5, 0.75

SELECT
    x.roundamt, ROUND(  (@value - FLOOR(@value)) / roundamt, 0 ) * roundamt + FLOOR(@value)
FROM   
    ( VALUES (0.02), (0.25), (0.5), (0.75) )x(roundamt)

enter image description here

like image 60
Sumtraveller Avatar answered Nov 09 '22 04:11

Sumtraveller


use ROUND(value/25, 2) * 25 like this:

Example1:

DECLARE @value DECIMAL(18, 2)
SET @value = 1.126
SELECT CAST(ROUND(@value/25, 2) * 25 as numeric(18,2)) AS rounded_val

Output:

1.25

Example2:

DECLARE @value DECIMAL(18, 2)
SET @value = 1.124
SELECT CAST(ROUND(@value/25, 2) * 25 as numeric(18,2)) AS rounded_val

Output:

1.00
like image 31
nil Avatar answered Nov 09 '22 04:11

nil


select Sample,
  Round( ( Sample + Sign( Sample ) * 0.125 ) * 4, 0, 1 ) / 4.0 as Rounded
  from ( values ( 0.0 ), ( 0.1 ), ( 1.125 ), ( 0.25 ), ( 10.5 ),
    ( -0.75 ), ( -0.875 ), ( -1.12 ), ( -1.125 ) )
    as Samples( Sample )

Note that ROUND can be used to truncate the fractional part of a value regardless of the sign. FLOOR will always return a value equal to or less than the original value, which can be problematic when the value is negative.

like image 20
HABO Avatar answered Nov 09 '22 04:11

HABO