Search code examples
sql-serversql-server-2008data-conversion

Is there a built-in function that can convert numbers into words in sql server


I have a table currency:

Dollar  
------  
10   
100  
1000    
120.20  

O/P

Dollar  
--------    
Ten dollar  
Hundred dollar  
One Thousand dollar  
One Hundred Twenty dollar and Twenty cents

Solution

  • There is a function, Util_ToWords, in the Free version of the SQL# SQLCLR library that I wrote that does this (well, without the "dollar(s)" and "cents" words added):

    SELECT SQL#.Util_ToWords(10); -- Ten
    SELECT SQL#.Util_ToWords(100); -- One Hundred
    SELECT SQL#.Util_ToWords(1000); -- One Thousand 
    SELECT SQL#.Util_ToWords(120.20); -- One Hundred Twenty and 20
    SELECT SQL#.Util_ToWords(212); -- Two Hundred Twelve
    SELECT SQL#.Util_ToWords(123097.4);-- One Hundred Twenty Three Thousand, Ninety Seven and 40
    

    The following example injects the "dollar(s)" and "cents" words into the return value (which was originally intended for printing on checks):

    DECLARE @Amount MONEY = 2.08;
    
    ;WITH cte AS
    (
      SELECT N' dollar' + CASE WHEN @Amount >= 1.00 AND @Amount < 2.00 THEN N''
                  ELSE N's'
             END AS [Currency],
             SQL#.Util_ToWords(@Amount) AS [Words]
    )
    SELECT CASE CHARINDEX(N' and ', cte.[Words])
               WHEN 0 THEN cte.[Words] + cte.[Currency]
               ELSE STUFF(cte.[Words], CHARINDEX(N' and ', cte.[Words]), 0, cte.[Currency])
                    + N' cents'
           END
    FROM cte;
    

    Returns:

    Two dollars and 08 cents