Question

Has anyone encountered the following where when you divide a number in SQL a random number of trailing zeros are appended?...

SELECT 8.95/10   ... results in 0.895000

If you have encountered this, what is the reason for the addition of the zeros?

UPDATE: I am aware that casting the result to FLOAT will remove the 0's

Was it helpful?

Solution

First of all, seeing trailing zeros or anything when querying in SSMS is not because it's something special with the DB engine, but it's always the result of the internal query result formating used for displaying. After all, all numbers are just binary values in some representation that at some point gets translated to strings for displaying.

Anyway, the real reason is because of the datatypes involved, and how SSMS decides to display them. When doing those calculations, SQL Server must decide what datatype the result will be, based on the types of the inputs, and in that particular case it was numeric(7,6). You can easily see the result types by saving the result to a temp table and running sp_columns on that:

SELECT 8.95 AS dividend,10 AS divider,8.95/10 AS result INTO #temp ;
EXEC tempdb..sp_columns '#temp' ;
SELECT * FROM #temp ;
DROP TABLE #temp ;

In my case it returned this (among other uninteresting things for now):

COLUMN_NAME    TYPE_NAME     PRECISION     LENGTH    SCALE
dividend       numeric       3             5         2
divided        int           10            4         0
result         numeric       7             9         6

Playing with castings in various places in the division will only change the resulting data types. The interesting fact is the Scale for the result column, note that it's a 6. That's exactly the number of decimal places that SSMS decides to display for the NUMERIC data type, regardless of the actual value. FLOAT don't have this formating from SSMS, which is why the casting eliminates the trailing zeros. Of course, when using the DB from outside SSMS, the formating will depend on the calling application and will not be subject to all this.

As another example of this behavior, just try SELECT CAST(1 AS NUMERIC(18,10)) and see that it shows 1.0000000000.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top