[quoted text, click to view] On Wed, 26 Apr 2006 09:35:18 -0500, Christoph wrote:
>Could someone explain to me what's going on here? I'm obviously missing
>something
Hi Christoph,
No problem. Just start by going to Books Online and finding the subject
"Data Type Precedence".
[quoted text, click to view] > DECLARE @annualisedPremium money
> DECLARE @totalPolicyPremium money
>
> SELECT @totalPolicyPremium = 2500.0000
> SELECT @annualisedPremium = (( @totalPolicyPremium / 365 ) * 365 )
For the parenthesed expression ( @totalPolicyPremium / 365 ),
@totalPolicyPremium is money and 365 is int. According to data type
precedence, 365 is cast to money and the result is a money value as
well. The result of the division is truncated to four decimals: 6.8493.
For the multiplication, we (again) have money and int. The int constant
365 is converted to money and the multiplication is done. The result is
6.8493 * 365.0000 = 2499.9945.
[quoted text, click to view] > DECLARE @annualisedPremium money
> DECLARE @totalPolicyPremium money
>
> SELECT @totalPolicyPremium = 2500.0000
> SELECT @annualisedPremium = (( 2500 / 365 ) * 365 )
Here, 2500 and 365 are both integer constants. The result of 2500/365 is
therefor integer as well - 2500/365, truncated to integer, is 6.
Multiply that with 365 to get the result of 2190. An assignment to
@annualisedPremium, this gets cast to money: 2190.0000
[quoted text, click to view] > DECLARE @annualisedPremium money
> DECLARE @totalPolicyPremium money
>
> SELECT @totalPolicyPremium = 2500.0000
> SELECT @annualisedPremium = (( 2500.0000 / 365 ) * 365 )
In this case, SQL Server treats the constant 2500.0000 as numeric(8,4).
According to data type precedence, the integer 365 is cast to numeric as
well (probably numeric(3,0), but I didn't check), and the result of the
division is also numeric - but in this case, it is numeric(12,8). (The
rules for determining length and mantissa of a numeric division result
are also documented in BOL, but I'm too lazy to look them up right now,
so I just did a test to find out).
The result of the division, after truncation to numeric(12,8) is equal
to 6.84931506. Multiplying this with 365 (cast to numeric, of course)
yields 2499.99999690. The assignment to @annualisedPremium forces
conversion to money - the result is rounded to 2500.0000
[quoted text, click to view] >Any help/pointers would be greatly appreciated!
Never use the money datatype in calculations. Best not use the money
datatype at all, but if you must, use CAST to force a more sensible
datatype in each calculation.
Take care to avoid using only integer datatype in division, except if
you really WANT to lose the fractional part.
--