locked
division in SQL results in 0 RRS feed

  • Question

  • division in SQL results in 0 Posted on:  01/09/2006 09:20:13
      



    declare @x int, @y int, @f float
    set @x = 100
    set @y = 2000
    set @f = @x / @y
    print @x
    print @y
    print @f


    in the above code @f prints as 0 instead of 0.05
    how would i correct that?
    Monday, January 9, 2006 5:40 PM

Answers

  • Try this:

    declare @x int, @y int, @f float
    set @x = 100
    set @y = 2000
    set @f = @x / (@y * 1.0)
    print @x
    print @y
    print @f

     

    Monday, January 9, 2006 6:55 PM

All replies

  • Try this:

    declare @x int, @y int, @f float
    set @x = 100
    set @y = 2000
    set @f = @x / (@y * 1.0)
    print @x
    print @y
    print @f

     

    Monday, January 9, 2006 6:55 PM
  • just try this

     

    declare @a float,@b float
    declare @c  float
    set @a =cast(56278 as float)
    set @b= cast(79089 as float)
    set @c = @a / @b
    print @a
    print @b
    print @c

     

    Friday, October 26, 2007 10:23 AM
  • What is happening is that you divide an integer value by another integer value => result is an integer. You can read up on this in BOL when you search for data type precedences (I think so). A simple way to prevent this is to use

     

    set @f = @x * 1.0 / @y

    Friday, October 26, 2007 10:51 AM
  •  

    just try this using cast

    declare @a int,@b int
    declare @C float
    set @a = 100
    set @b=200
    set @c= cast(@a as float)/cast(@b as float)
    print @C

    Monday, October 29, 2007 7:18 AM
  • set @f = @x*1.0 / @y*1.0
    Wednesday, November 6, 2013 8:50 AM