开发者

How to compute the modulus of a float in TSQL?

The modulus function in Microsoft SQL Server only works on certain data types.

Accordi开发者_StackOverflowng to the MSDN Article [1] on the modulus operator, you normally would use modulus like this...

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.

However that doesn't work when the dividend is a float data type. The answer we came up with is listed below for future reference.

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


Cast to decimal/numeric, modulo, and cast back?

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


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


This is the answer I came up with. It only applies if the dividend is a float, not the divisor as well.

( cast(dividend as integer) % divisor ) + ( dividend - cast(dividend as integer))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜