取最大公因數
Create FUNCTION dbo.GCD(@a INT, @b INT)
RETURNS INT
AS
BEGIN
--最大公因數
WHILE @b != 0
BEGIN
DECLARE @temp INT;
SET @temp = @b;
SET @b = @a % @b;
SET @a = @temp;
END
RETURN @a;
END;
AS
BEGIN
--最大公因數
WHILE @b != 0
BEGIN
DECLARE @temp INT;
SET @temp = @b;
SET @b = @a % @b;
SET @a = @temp;
END
RETURN @a;
END;
英吋轉分數
Create function dbo.FeetToFraction (@decimal_value DECIMAL(18, 2))
returns NVARCHAR(50)
AS
BEGIN
--英呎轉分數
declare @Int int;
DECLARE @whole_part DECIMAL(18, 2);
DECLARE @fraction_part DECIMAL(18, 2);
DECLARE @numerator DECIMAL(18, 2);
DECLARE @denominator DECIMAL(18, 2);
DECLARE @gcd_value DECIMAL(18, 2);
DECLARE @fraction_string NVARCHAR(50);
-- 取得整數部分和小數部分
SET @Int = FLOOR(@decimal_value); --整數
SET @fraction_part = @decimal_value - @Int; --小數
-- 初始分母為16
SET @denominator = 16;
-- 將小數部份乘以 0.75 * 12
SET @numerator = @fraction_part * 12;
-- 取相乘後的整數
SET @whole_part = FLOOR(@numerator); --整數
SET @fraction_part = @numerator - @whole_part; --小數
Set @fraction_part = FLOOR(@fraction_part * @denominator)
-- 求分子和分母的最大公因数
SET @gcd_value = dbo.GCD(@fraction_part, @denominator);
WHILE @gcd_value > 1
BEGIN
SET @fraction_part = @fraction_part / @gcd_value;
SET @denominator = @denominator / @gcd_value;
SET @gcd_value = dbo.GCD(@fraction_part, @denominator);
END;
-- 組合成分數
if convert(int, @fraction_part) <> 0
begin
SET @fraction_string = CONCAT(@Int, ''' ' ,
convert(int, @whole_part), '-',
convert(int, @fraction_part), '/', convert(int, @denominator),'"');
end
else
begin
SET @fraction_string = CONCAT(@Int, ''' ' ,
convert(int, @whole_part), '"');
end
Return @fraction_string;
END;
沒有留言:
張貼留言