Friday, August 11, 2006

How to find whether a decimal number is divisible by another decimal number?

Normally for finding whether an integer is divisible by another integer we would use Modulo function (%). But what if we have two decimal values? The below code snippet would help you in that case.

Declare @decValueOne decimal(10,2), @decValueTwo decimal(10,2)
Declare @tempResultCeiling int, @tempResultFloor int

Set @decValueOne = 21.3
Set @decValueTwo = 7.1

--Normal method which would work for two integer values
Select cast(@decValueOne as int) % cast(@decValueTwo as int)

Select @tempResultCeiling = Ceiling(@decValueOne / @decValueTwo)
Select @tempResultFloor = Floor(@decValueOne / @decValueTwo)

Select Case
When @tempResultCeiling = @tempResultFloor
then 'Evenly Divisible'
Else 'It''s NOT divisible'
End as 'Result'

If you run the above code snippet the result would be 'Evenly Divisible' as 21.3 is three times 7.1
Technorati tags: , ,

1 comment:

denz said...

I wonder why modulo (%) doesn't do what your snippet is doing when using this code on integers yeilds the same result with %. Isn't it?