Number of decimal places returned by dividing integers?

--in sql server 2005.

SELECT 5/13;   ----> 0  
SELECT Cast(5/13 AS real); --> 0  
SELECT 5.00/13.00; --> 0.3846153 
SELECT cast(5/13 as decimal(10, 2));        --> 0.00 
SELECT cast(5 as decimal)/cast(13 as Decimal); --> 0.3846153846153846153

Is there a global setting for number of decimal places returned by dividing integers? All I need is to have the result as .38

1 answer

  • answered 2018-01-13 21:12 Gordon Linoff

    There is no global setting. (That is the question you are asking.)

    When you divide two integers, the result is an integer. You simply want to express the value to two decimal places. John Capelletti has the right answer in a comment. Convert the values to non-integers and then convert back to the format you want. I normally do this by multiplying by 1.0:

    select cast((5 * 1.0 / 13) as decimal(10, 2)
    

    There are quite arcane rules for the number of decimal places produced when you do arithmetic on decimal values.