Search This Blog

Calculation on Numbers Resulting it as a Integer values not in decimal in SQL

Calculation on Numbers Resulting it as a Integer values not in decimal  in SQL

A comman mistake while performing calculation  in sql query  not getting exact output or Result
In order to know more about this topic run a simple query as below.

select 13/2

Output 6 

But not exact as the output should come as 6.5

Try to convert or cast it as float or decimal

select CAST((13/2) as float)

Output 6 

select convert(decimal(12,0),(13/2))

Output 6 

None of above query is giving exact result 

Now run this one

select cast(13 as float)/2

Output 6.5

select 13/cast(2 as float)

Output 6.5

The Reason for above 2 queries not giving exact output is we are getting the result and after that we were casting it to float of decmial values 
In last 2 query what we did is in the calculation time only we have casted or coverted the denominator or numerator into float so int divided by float of float divided by Int will result as Float.

Note : Float has higher preference then int .In order to check Datatype precedence go to msdn below link

No comments:

Post a Comment