Search code examples
sql-serversql-server-2008divisionrounding

How to get a float result by dividing two integer values using T-SQL?


Using T-SQL and Microsoft SQL Server I would like to specify the number of decimal digits when I do a division between 2 integer numbers like:

select 1/3

That currently returns 0. I would like it to return 0,33.

Something like:

select round(1/3, -2)

But that doesn't work. How can I achieve the desired result?


Solution

  • The suggestions from stb and xiowl are fine if you're looking for a constant. If you need to use existing fields or parameters which are integers, you can cast them to be floats first:

    SELECT CAST(1 AS float) / CAST(3 AS float)
    

    or

    SELECT CAST(MyIntField1 AS float) / CAST(MyIntField2 AS float)