Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server format decimal places with commas

Tags:

sql

sql-server

How can I convert the decimal values to have some commas?

this Helps me. But my problem the decimal places are set to 2 only..I want the decimal to be 2, 3, or 4..example

1,234.123   or    1,234.12345

I tried

convert(varchar, convert(decimal(18, 4), 1234.1234567), 1) 

Output : 1234.1234

There is no comma. But if I use money the decimal are 2 only

convert(varchar, convert(money, 1234.1234567), 1)

Output : 1,234.12

like image 913
Snippet Avatar asked Nov 06 '12 06:11

Snippet


2 Answers

Thankfully(?), in SQL Server 2012+, you can now use FORMAT() to achieve this:

FORMAT(@s,'#,0.0000')


In prior versions, at the risk of looking real ugly

[Query]:

declare @s decimal(18,10);
set @s = 1234.1234567;
select replace(convert(varchar,cast(floor(@s) as money),1),'.00',
    '.'+right(cast(@s * 10000 +10000.5 as int),4))

In the first part, we use MONEY->VARCHAR to produce the commas, but FLOOR() is used to ensure the decimals go to .00. This is easily identifiable and replaced with the 4 digits after the decimal place using a mixture of shifting (*10000) and CAST as INT (truncation) to derive the digits.

[Results]:

|   COLUMN_0 |
--------------
| 1,234.1235 |

But unless you have to deliver business reports using SQL Server Management Studio or SQLCMD, this is NEVER the correct solution, even if it can be done. Any front-end or reporting environment has proper functions to handle display formatting.

like image 149
RichardTheKiwi Avatar answered Oct 14 '22 19:10

RichardTheKiwi


without considering this to be a good idea...

select dbo.F_AddThousandSeparators(convert(varchar, convert(decimal(18, 4), 1234.1234567), 1))

Function

-- Author:      bummi
-- Create date: 20121106
CREATE FUNCTION F_AddThousandSeparators(@NumStr varchar(50)) 
RETURNS Varchar(50)
AS
BEGIN
declare @OutStr varchar(50)
declare @i int
declare @run int

Select @i=CHARINDEX('.',@NumStr)
if @i=0 
    begin
    set @i=LEN(@NumStr)
    Set @Outstr=''
    end
else
    begin   
     Set @Outstr=SUBSTRING(@NUmStr,@i,50)
     Set @i=@i -1
    end 


Set @run=0

While @i>0
    begin
      if @Run=3
        begin
          Set @Outstr=','+@Outstr
          Set @run=0
        end
      Set @Outstr=SUBSTRING(@NumStr,@i,1) +@Outstr  
      Set @i=@i-1
      Set @run=@run + 1     
    end

    RETURN @OutStr

END
GO
like image 43
bummi Avatar answered Oct 14 '22 18:10

bummi