Search code examples
sql-servert-sqlformatsignedfinancial

SQL Server 2005 - Format a decimal number with leading zeros (including signed decimals!)


I need to format numbers like:-

1.99
21.34
1797.94
-300.36
-21.99
-2.31

Into a format mask of 0000.00, using SQL-Server 2005 T-SQL. Preserving the signed integers and the decimals after the dot. This would be used for text file exports for a financial system. It requires it to be in this format.

e.g.-

0001.99
0021.34
1794.94
-0300.36
-0021.99
-0002.31

Previously, it was done in MS Access as Format([Total],"0000.00") but SQL-Server doesn't have this function.


Solution

  • ;WITH t(c) AS
    (
    SELECT 1.99 UNION ALL 
    SELECT 21.34  UNION ALL 
    SELECT 1797.94  UNION ALL 
    SELECT -300.36  UNION ALL 
    SELECT -21.99  UNION ALL 
    SELECT -2.31 
    )
    SELECT  
         CASE WHEN SIGN(c) = 1 THEN '' 
              ELSE '-' 
         END + REPLACE(STR(ABS(c), 7, 2), ' ','0') 
    FROM t
    

    Returns

    0001.99
    0021.34
    1797.94
    -0300.36
    -0021.99
    -0002.31