Money Precision Issues
Many developers like MONEY
data type as it tends to be faster during computations and byte cheaper (arguably). Still in the next few examples, I am going to show an issue that can lead to possible loss of precision.
Let us try the following code:
decalare @d1 money, @d2 money, @res money
set @d1 = 18.4172
set @d2 = 1.00
set @res = @d2/@d1
select @res
0,054297
and by all mathematical rules should be rounded to 0,0543
. Still, the query result is 0,0542
.
Let’s look at another example:
decalare @d1 money, @d2 money, @res money
set @d1 = 18.4172
set @d2 = 1.1562
set @res = @d1*@d2
select @res
This kind of behaviour is called banker’s rounding. However, if you use SQL Server DB combined with .NET application, you may encounter precision loss as .NET doesn’t use banker’s rounding for decimal data type by default.
One of the possible solutions is to cast money to more precise data type before such operations. The following example works properly:
decalare @d1 money, @d2 money, @res money
set @d1 = 18.4172
set @d2 = 1.1562
set @res = convert(decimal(19,4) @d2)/@d1
select @res