Link to home
Start Free TrialLog in
Avatar of Bharat Guru
Bharat Guru

asked on

How to convet fraction to decimal

How to convert fraction to decimal using tsql for example
   select   myfunction(25 1/8)
   select   myfunction(25 1/16)

should return as 25.125  
should return as 25.0625
Avatar of Igor-K
Igor-K
Flag of United Kingdom of Great Britain and Northern Ireland image

Could you show the syntax of your function?  You could be receiving 0 when doing 1/8 because SQL server treats them as ints and the result as int that would be 0.  If you would indicate that one of them is float then result would be float as well.

For Example:
select convert(float,1)/8
declare @float float
set @float = 8
select 1/@float
set @float = 1
select @float/8
Give this a try.
Btw, never use float. Float is not precise. Use decimal instead. (I've used 9 decimals but adjust it to your convenience)

create function dbo.fractodecimal(@frac varchar(40))
returns decimal(10,9)
as
	declare @retnumber decimal(10,9)
	declare @frac_tmp varchar(50)
 
	set @retnumber = convert(decimal(10,9), left(@frac, charindex(' ', @frac)))
	set @frac_tmp = right(@frac, charindex(' ', reverse(@frac)) - 1)
 
	select 	@retnumber = @retnumber + convert(decimal(10,9), left(@frac_tmp,charindex('/',@frac_tmp)-1)) / 
		convert(decimal(10,9),right(@fract_tmp, charindex('/', reverse(@frac_tmp)) - 1))
 
	return(@retnumber)
 
go;
 
--and you call it like this:
 
select dbo.fractodecimal('2 1/2')

Open in new window

Avatar of Patrick Matthews
Hello patel100,

Here is my take on it.  It returns a float, and ralmada's advice regarding float should be considered.

CREATE FUNCTION dbo.myfunction (@StringIn varchar(100))
RETURNS float
AS BEGIN
      DECLARE @IntegerPart float, @FracPart float, @Fraction varchar(100), @Numerator float,
            @Denominator float, @Answer float
      IF CHARINDEX(' ', @StringIn) = 0
            SET @Answer = CONVERT(float, @StringIn)
      ELSE BEGIN
            SET @IntegerPart = CONVERT(float, LEFT(@StringIn, CHARINDEX(' ', @StringIn) - 1))
            SET @Fraction = SUBSTRING(@StringIn, CHARINDEX(' ', @StringIn) + 1, 100)
            SET @Numerator = CONVERT(float, LEFT(@Fraction, CHARINDEX('/', @Fraction) - 1))
            SET @Denominator = CONVERT(float, SUBSTRING(@Fraction, CHARINDEX('/', @Fraction) + 1, 100))
            SET @Answer = @IntegerPart + @Numerator / @Denominator
      END
      RETURN @Answer
END

Regards,

Patrick
ASKER CERTIFIED SOLUTION
Avatar of ralmada
ralmada
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial