Article published in SQL Server Central on 2009/03/26
In some scenarios we need to be able to round or truncate decimals to achieve correct calculation results. In SQL we have ROUND, which can do either of these. It rounds like we are used to – 0.5 rounds up to 1, can round up or down and we rarely get a project where as a part of the requirements we are implementing our own rounding or truncation algorithm.
However, in MDX we have Round() which performs a “strange” operation – bankers’ rounding, which our business users have usually not been exposed to, and if we decide to truncate to an integer number through casting with Int or cInt, we also get some strange results. To illustrate the problem with MDX please consider the value of these expressions:
Round(2.15, 1) = 2.2
Round(2.25, 1) = 2.2
Round(2.35, 1) = 2.4
Round(2.45, 1) = 2.4
Int(1.9) = 1
Int(-1.9) = -2
cInt(1.9) = 1
These are usually considered wrong, because they are not the obvious results. Even though they are mathematically well founded, if we round 2.25 to 2.2, our users will come back at us with wrong numbers on their reports. Same goes for “trimming” -1.9 to -2.
To resolve the first problem with rounding, we can use our own math formula:
Fix([Measures].[???] * Factor + 0.5 * Sgn([Measures].[???])) / Factor
Where Factor is the rounding factor – 1 for 0 decimal places, 10 for 1 and so on (defined by 1/Factor). Of course, Factor of 0 will give us Div by 0 error. (Reference: http://support.microsoft.com/kb/196652)
If we have the Excel function libraries intalled on our server, we can also simply use Excel!Round() as Chris Webb advises.
As for the Int and cInt in MDX, we can use the Fix() VBA function to remove decimal places:
Fix(1.9) = 1
Fix(-1.9) = -1
Also, for truncation of values to a certain decimal point in MDX, we can use the following formula:
All we need to adjust in order to change the decimal places is to replace 10^1 with another power of 10 – in example, to truncate 3.156 to 3.15 we can use: Fix(3.156*10^2)/10^2. To make things simpler, in all our formulas the power of 10 is what determines how many decimal paces we need to round to; negative powers will give us rounding to tens, thousands and so on. If we use ^0 we will round to whole numbers.
Using these we can avoid bankers’ rounding and some strange results with converting to integers in MDX.