Wednesday 7 March 2012

How to Round to 2 decimal places without Round function

Today, Someone asked me how to round float value to 2 decimal places without using T-SQL Round function. Let me know your thoughts for below T-SQL block.

Declare
      @MyValue Float = 3.1471,
      @IntPart1 int = 0 ,
      @intPart2 int = 0
Select @IntPart1=@MyValue
select @intPart2 = (@MyValue - @IntPart1)*100
If (@MyValue  - ( Cast(@IntPart1 AS Float) + Cast(@intPart2 AsFloat)/100))*10000 > 50
      Select Cast(@IntPart1 AS Float) + Cast(@intPart2+As Float)/100 ASRound1
Else
      Select Cast(@IntPart1 AS Float) + Cast(@intPart2 As Float)/100  AS Round1