2010-06-23 78 views
1

Microsoft SQL Server中的模數函數僅適用於某些數據類型。如何計算TSQL中的float的模數?

根據MSDN文章[1]模運算符,您通常會使用模數是這樣的...

dividend % divisor 

dividend 
Is the numeric expression to divide. dividend must be a valid 
expression of any one of the data types in the integer and 
monetary data type categories, or the numeric data type. 

divisor 
Is the numeric expression by which to divide the dividend. 
divisor must be any valid expression of any one of the data 
types in the integer and monetary data type categories, or 
the numeric data type. 

然而,當分紅是一個浮點數據類型不起作用。下面列出了我們提出的答案以供將來參考。

[1] http://msdn.microsoft.com/en-us/library/ms190279.aspx

+2

這是因爲,如果你正在做數學計算,你不應該在float數據類型存儲數據。這是一種不精確的數據類型,會導致舍入問題。 – HLGEM 2010-06-23 19:44:00

+0

好點。我沒有想到通過錯誤消息的問題。感謝那一點智慧。 – 2010-06-23 19:52:50

回答

4

強制轉換爲十進制/數字,模和回頭?

CAST(CAST(TheInaccurateFloatValue AS decimal(38,19)) % ModuloValue AS float) 
+0

另一個好的解決方案。 – 2010-06-24 04:01:34

1

這是我想出了答案。它只適用於股息是浮動的,而不是除數。

(cast(dividend as integer) % divisor) + (dividend - cast(dividend as integer)) 
1
declare @A float = 2.5 
declare @B float = 1.1 

-- Expected: A % B = 2.5 % 1.1 = 0.3 

select @A - floor(@A/@B) * @B