Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 a basic question about division in SQL

Author  Topic 

mavershang
Posting Yak Master

111 Posts

Posted - 2008-12-03 : 13:04:46
I am a rookie with a very basic question.

I want to calculate sth like 1/2, and I want to get the result of 0.5.But when I use "/", what I get is always "0".
So how to figure it out?

Thanks

sodeep
Master Smack Fu Yak Hacker

7174 Posts

Posted - 2008-12-03 : 13:06:22
select 1/2.0

output:
.500000
Go to Top of Page

revdnrdy
Posting Yak Master

220 Posts

Posted - 2008-12-03 : 13:08:44
This has to do with integer division

For example if you type select 3/4 in sql you will get 0 instead of .75

What you need to do is simply cast the numerator or denominator to a float. This can be done by multiplying by 1.0.

example: select (1.0*3)/4 or select 3/(1.0*4)

If you are referencing a variable it becomes
(1.0* somevar)/someothervar

there are other ways but this is just a quick & easy method.

r&r
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-12-03 : 13:13:38
http://sqlblogcasts.com/blogs/madhivanan/archive/2008/01/16/beware-of-implicit-conversions.aspx
Go to Top of Page

mavershang
Posting Yak Master

111 Posts

Posted - 2008-12-03 : 13:23:23
Thank you guys. That is very helpful
Go to Top of Page
   

- Advertisement -