Rounding down decimal numbers in SQL Server 2008

前端 未结 3 763
傲寒
傲寒 2020-12-10 06:21

I read all rounding functions of T-SQL like Round, Floor, and Ceil, but none of them has rounded down decimal numbers correctly for me

3条回答
  •  有刺的猬
    2020-12-10 06:30

    As per @J0e3gan 's anwser, Sql Server's Round allows rounding to the nearest powers of 10 using the length parameter, where length is 10^(-length), e.g.

    length = 0 : 10 ^ 0 = nearest 1
    length = 3 : 10 ^ -3 = nearest .001
    length = -3 : 10 ^ 3 = nearest 1000
    

    etc

    However, in general, with a simple 1-based rounding function - e.g. (Sql Round with Length=0) to round to an arbitrary value of "nearest N" - with the formula:

    round(X / N) * N
    

    e.g. nearest 100

    select round(12345 / 100.0, 0) * 100.0 -- 12300
    select round(-9876 / 100.0, 0) * 100.0 -- -9900
    select round(-9849 / 100.0, 0) * 100.0 -- -9800
    

    ... Nearest 0.5

    select round(5.123 / 0.5, 0) * 0.5 -- 5.000
    select round(6.499 / 0.5, 0) * 0.5 -- 6.500
    select round(-4.499 / 0.5, 0) * 0.5 -- -4.50
    

    ... Nearest 0.02

    select round(5.123 / .02, 0) * .02 -- 5.12
    select round(-9.871 / .02, 0) * .02 -- -9.88
    

    etc

    Remember that the type used for the divisors must be numeric / decimal or float.

提交回复
热议问题