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
Thankfully(?), in SQL Server 2012+, you can now use FORMAT() to achieve this:
FORMAT(@s,'#,0.0000')
[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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With